0. 引子
本例是从 gtest-1.5.0 自带的 sample 中的 sample1 改写而来,笔者只添加了一个求 n 的阶层的函数,如下。
void Factorial(int n, int & result )
{
result = 1;
for (int i = 1; i <= n; i++)
result *= i;
}
目的是想测试像这样将返回值放在参数中返回的函数。
对于该函数,添加的单元测试代码如下。
TEST (FactorialTest , Mytest )
{
int result = 0;
Factorial (5, result);
EXPECT_EQ (120, result);
}
1. 要测试的代码
要测试的代码 (Sample.h) 代码如下。
要测试的代码 (Sample.cpp) 代码如下。
2. 单元测试代码
单元测试代码 (test.cpp) 如下。
3. 编译
3.1 Linux 平台
makefile 文件,请参考 “ Linux平台如何编译使用Google test写的单元测试? ”
3.2 Win32 平台
Make.bat 文件,请参考 “ Win32 平台如何编译使用 Google test 编 写的单元测试? ” 。
4. 运行结果
4.1 Linux 平台
运行结果如下。
# ./test
Running main() from gtest_main.cc
[==========] Running 7 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 4 tests from FactorialTest
[ RUN ] FactorialTest.Negative
[ OK ] FactorialTest.Negative (0 ms)
[ RUN ] FactorialTest.Zero
[ OK ] FactorialTest.Zero (0 ms)
[ RUN ] FactorialTest.Positive
[ OK ] FactorialTest.Positive (0 ms)
[ RUN ] FactorialTest.Mytest
[ OK ] FactorialTest.Mytest (0 ms)
[----------] 4 tests from FactorialTest (0 ms total)
[----------] 3 tests from IsPrimeTest
[ RUN ] IsPrimeTest.Negative
[ OK ] IsPrimeTest.Negative (0 ms)
[ RUN ] IsPrimeTest.Trivial
[ OK ] IsPrimeTest.Trivial (0 ms)
[ RUN ] IsPrimeTest.Positive
[ OK ] IsPrimeTest.Positive (0 ms)
[----------] 3 tests from IsPrimeTest (0 ms total)
[----------] Global test environment tear-down
[==========] 7 tests from 2 test cases ran. (0 ms total)
[ PASSED ] 7 tests.
7 个测试均通过。
4.2 Win32 平台
运行结果如下。