- 什么是gtest
维基百科解释如下,简言之,就是一个C++的单元测试框架,可用于Window平台、Mac OS、Linux、Unix等多种平台。帮你更好地从白盒的角度对代码进行测试。
Google Test is a unit testing library for the C++ programming language, based on the xUnit architecture.[1]The library is released under the BSD 3-clause license.[2] It can be compiled for a variety of POSIX andWindows platforms, allowing unit-testing of C sources as well as C++ with minimal source modification. The tests themselves could be run one at a time, or even be called to run all at once. This makes the debugging process very specific and caters to the need of many programmers and coders alike.
- 官方主页和下载
官方主页:
https://github.com/google/googletest
下载链接:
https://codeload.github.com/google/googletest/zip/release-1.8.0
- 如何使用
新建一个win32控制台app
在VS中配置三点
- 设置gtest头文件路径
比如我将下载好的gtes文件解压到了桌面,此处设置到include路径即可
- 设置gtest.lib路径
在googletest文件夹中找到msvc文件夹(意思是给vs项目用的),找到debug下的gtestd.lib (d为debug的意思)
- Runtime Library设置
最后配置代码生成中的运行库为多线程即可。
具体使用入门:
假设有一个被测函数为Foo(),功能为求最大公约数,我们编写测试用例对其进行测试。
int Foo(int a, int b)
{
if (a == 0 || b == 0)
{
throw "don't do that";
}
int c = a % b;
if (c == 0)
return b;
return Foo(b, c);
}
整个代码见下图:
-
- 在_tmain() 中调用
testing的构造函数,然后return RUN_ALL_TESTS()即可对被测函数进行测试。
- 被测函数:
- 在_tmain() 中调用
-
- 定义测试用例的方法是使用关键字 TEST(TestSuiteName,TestCaseName) 定义测试用例:
编写多条测试用例时,直接使用TEST(XX, XX)进行定义即可,不需要编写新的函数名称,其中最简单的断言有EXPECT_*和ASSERT_*两种,区别如下:
- EXPECT_* 失败时,案例继续往下执行。
- ASSERT_* 失败时,直接在当前函数中返回,当前函数中ASSERT_*后面的语句将不会执行。
文章评论(0)