Windows Visual Studio下安装和使用google test(gtest)

Windows Visual Studio下安装和使用google test(gtest)

2014-09-27 23:40:01 officercat 阅读数 14804更多

分类专栏: 编程技术 开发环境 C++

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/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

 

 
  1. #pragma once

  2. int fun(int a, int b);

sample.cpp

 
  1. #include"stdafx.h"

  2. #include"sample.h"

  3. int fun(int a, int b)

  4. {

  5. return (a-b);

  6. }

 

 
  1. #include "stdafx.h"

  2. #include "gtest\gtest.h"

  3. #include "sample.h"

  4.  
  5.  
  6. TEST(fun, case1)

  7. {

  8. EXPECT_LT(-2, fun(1, 2));

  9. EXPECT_EQ(-1, fun(1, 2));

  10. ASSERT_LT(-2, fun(1, 2));

  11. ASSERT_EQ(-1, fun(1, 2));

  12. }

  13.  
  14. int _tmain(int argc, _TCHAR* argv[])

  15. {

  16. testing::InitGoogleTest(&argc, argv);

  17. return RUN_ALL_TESTS();

  18. }

  19.  


 

因为要用到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里单元测试会在一个单独的工程里,这只是一个简单的例子。

 

参考文章:

 

[C++]在Visual Studio 2010中使用Google Test - 配置

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值