Windows Visual Studio下安装和使用google test(gtest)
2014-09-27 23:40:01 officercat 阅读数 14804更多
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.youkuaiyun.com/officercat/article/details/39621423
之前写过一篇《Linux下Google Test测试环境安装和使用,实战总结》 ,既然google test是跨平台的,我们也有很多代码工程也是跨平台的,在windows下配置google test 开发环境也是很有意义的。
首先下载google test,http://code.google.com/p/googletest/可以下载到最新版,当然这个网站经常被屏蔽,所以可以直接到其他网站下一个源代码压缩包,现在基本上gtest-1.6版是够用的,下载下来后,放到一个合适的位置,这里面的源文件在编译器中需要被引用到。
可以看到源代码文件夹里,有适应各种操作系统的编译脚本或者工程文件,比如cmake,make,msvc, msvc文件夹里就是一个支持visual studio的solution文件

打开gtest.sln,如果有需要,visual studio会自动升级我用的是visu studio 2012),可以发现里面有几个项目,其中gtest和gtest_main的产出是对google test编写有用的。

然后编译,会发现报错
error C2977 "std::tuple" too many template arguments
解决方法就是在每隔工程(project)的属性中的C++ --> Preprocessor (预处理)--> preprocessor defination (预处理定义)中增加
_VARIADIC_MAX=10

然后编译通过,debug和release都编译一遍,把编译出的gtest.lib,gtestd.lib, gtest_main.lib, gtest_maind.lib 都放到gtest根目录的lib文件夹下(lib和include位于同一级)。
为了方便使用,配置环境变量GTEST = D:\Program Files\gtest-1.6.0
然后我们建一个测试工程GTestDemo.sln,它包括简单的测试用代码
sample.h
-
#pragma once -
int fun(int a, int b);
sample.cpp
-
#include"stdafx.h" -
#include"sample.h" -
int fun(int a, int b) -
{ -
return (a-b); -
}
-
#include "stdafx.h" -
#include "gtest\gtest.h" -
#include "sample.h" -
TEST(fun, case1) -
{ -
EXPECT_LT(-2, fun(1, 2)); -
EXPECT_EQ(-1, fun(1, 2)); -
ASSERT_LT(-2, fun(1, 2)); -
ASSERT_EQ(-1, fun(1, 2)); -
} -
int _tmain(int argc, _TCHAR* argv[]) -
{ -
testing::InitGoogleTest(&argc, argv); -
return RUN_ALL_TESTS(); -
}

因为要用到gtest里的库,所以要增加对头文件和库的搜索路径,VC里有很多地方可以配置,我选择在项目属性--> C++-->General-->additional include Directories 里增加
$(GTEST)\include

在项目属性--> Linker-->General-->additional Library Directories 里增加

$(GTEST)\lib
在项目属性--> Linker-->Input-->additional Dependencies 里增加 gtest的lib,
如果是release设置,用gtest.lib,gtestd.lib; ruguoshidebug设置,用 gtest_main.lib, gtest_maind.lib。

然后编译,cmd运行编译出来的可执行文件,出现如下结果,这就是gtest的输出格式,比较好看,还有计时。

[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from fun
[ RUN ] fun.case1
[ OK ] fun.case1 (0 ms)
[----------] 1 test from fun (2 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (6 ms total)
[ PASSED ] 1 test.
更复杂的应用就有待进一步学习和发挥了,比如在visual studio里单元测试会在一个单独的工程里,这只是一个简单的例子。
参考文章:
本文详细介绍在Windows环境下,如何使用Visual Studio配置并使用Google Test(gtest)进行单元测试,包括下载、编译、环境变量设置及示例代码。
1292

被折叠的 条评论
为什么被折叠?



