本博客http://blog.csdn.net/livelylittlefish 贴出作者(三二一@小鱼)相关研究、学习内容所做的笔记,欢迎广大朋友指正!
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) 代码如下。
/** * GoogleTest test * platform: win32, visual studio 2005/2010; Linux, gcc4.1.2 */ #ifndef _SAMPLE_H_ #define _SAMPLE_H_ // Returns n! (the factorial of n). For negative n, n! is defined to be 1. int Factorial(int n); void Factorial(int n, int &result); // Returns true iff n is a prime number. bool IsPrime(int n); #endif
要测试的代码 (Sample.cpp) 代码如下。
/** * GoogleTest test * platform: win32, visual studio 2005/2010; Linux, gcc4.1.2 */ #include "sample.h" // Returns n! (the factorial of n). For negative n, n! is defined to be 1. int Factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) result *= i; return result; } void Factorial(int n, int &result) { result = 1; for (int i = 1; i <= n; i++) result *= i; } // Returns true iff n is a prime number. bool IsPrime(int n) { // Trivial case 1: small numbers if (n <= 1) return false; // Trivial case 2: even numbers if (n % 2 == 0) return n==2; // Now, we have that n is odd and n >= 3. // Try to divide n by every odd number i, starting from 3 for (int i = 3; ; i += 2) { // We only have to try i up to the squre root of n if (i > n/i) break; // Now, we have i <= n/i < n. // If n is divisible by i, n is not prime. if (n % i == 0) return false; } // n has no integer factor in the range (1, n), and thus is prime. return true; }
2. 单元测试代码
单元测试代码 (test.cpp) 如下。
/** * GoogleTest test * platform: win32, visual studio 2005/2010; Linux, gcc4.1.2 */ #include "sample.h" #include
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 平台
运行结果如下。
Technorati 标签: 单元测试;google test