从事开发也有两个年头了,但直到现在为止还没有真正给自己的代码做过单元测试。其实单元测试并不神秘,说简单点,就是为了便于测试你的代码而封装的一些模块。
最近从codeproject中看到一篇介绍google单元测试框架的文章,大感好奇,就试了试google的单元测试框架,感觉还真不错!!!就分享一下大家一起学习。
google单元测试框架的源码地址:
http://code.google.com/p/googletest/downloads/list
解压后,在msvc目录下有vs的solutions
gtest.sln - 静态编译Microsoft runtime libraries
gtest-md.sln - 使用DLL动态加载Microsoft runtime libraries
最后讲一个vs使用技巧
Project Properties->Configuration Properties->Build Events->Post-Build Event->Command Line中
最近从codeproject中看到一篇介绍google单元测试框架的文章,大感好奇,就试了试google的单元测试框架,感觉还真不错!!!就分享一下大家一起学习。
google单元测试框架的源码地址:
http://code.google.com/p/googletest/downloads/list
解压后,在msvc目录下有vs的solutions
gtest.sln - 静态编译Microsoft runtime libraries
gtest-md.sln - 使用DLL动态加载Microsoft runtime libraries
google单元测试框架的使用很步骤如下:
1、新建单元测试项目(不建议在你的源代码工程中直接使用)。
2、保证google单元测试框架和新建的单元测试项目,对于运行时库使用相同的加载方式。
运行时库配置: Project->Properties->Configuration Properties->C/C++->Code Generation->Runtime Library
3、包含google单元测试头文件
#include "include\gtest\gtest.h"
4、添加google单元测试框架编译出来的gtest.lib文件,Debug下是gtestd.lib文件。
5、添加测试代码。
注意:有趣的是google的单元测试框架的是通过宏来使用的,并不是函数。如:
/* TEST(test_case_name, test_name) is a predefined macro.
These are ordinary C++ functions that don't return a value.
In this function, along with any valid C++ statements you want to include,
use the various Google Test assertions to check values.
The test's result is determined by the assertions;
if any assertion in the test fails (either fatally or non-fatally),
or if the test crashes, the entire test fails. Otherwise, it succeeds.
*/
TEST(testCalc, MyFirstTest)//在这里测试你的代码
{
CCalc c;
EXPECT_EQ(8, c.Add(5,3));
EXPECT_EQ(2, c.Sub(5,3));
EXPECT_EQ(16, c.Mul(c.Add(5,3), c.Sub(5,3)));
}
int _tmain(int argc, _TCHAR* argv[])
{
/*The method is initializes the Google framework and must be called before RUN_ALL_TESTS */
::testing::InitGoogleTest(&argc, argv);
/*RUN_ALL_TESTS automatically detects and runs all the tests defined using the TEST macro.
It's must be called only once in the code because multiple calls lead to conflicts and,
therefore, are not supported.
*/
return RUN_ALL_TESTS();
}
最后讲一个vs使用技巧
Project Properties->Configuration Properties->Build Events->Post-Build Event->Command Line中
添加"$(TargetDir)$(TargetFileName)"语句可实现console中输出,在build中输出。
事例程序:http://download.youkuaiyun.com/detail/windows_nt/6741633