http://blog.csdn.net/livelylittlefish
http://code.google.com/p/googletest/
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)