现在的位置: 首页 > 综合 > 正文

使用Google Test的一个简单例子

2013年02月01日 ⁄ 综合 ⁄ 共 1269字 ⁄ 字号 评论关闭

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) 代码如下。

[c-sharp] view
plain
copy

  1. /** 
  2.  * GoogleTest test 
  3.  * platform: win32, visual studio 2005/2010; Linux, gcc4.1.2 
  4.  */  
  5. #ifndef _SAMPLE_H_  
  6. #define _SAMPLE_H_  
  7. // Returns n! (the factorial of n).  For negative n, n! is defined to be 1.  
  8. int Factorial(int n);  
  9. void Factorial(int n, int &result);  
  10. // Returns true iff n is a prime number.  
  11. bool IsPrime(int n);  
  12. #endif  

要测试的代码 (Sample.cpp) 代码如下。

  1. /** 
  2.  * GoogleTest test 
  3.  * platform: win32, visual studio 2005/2010; Linux, gcc4.1.2 
  4.  */  
  5. #include "sample.h"  
  6. // Returns n! (the factorial of n).  For negative n, n! is defined to be 1.  
  7. int Factorial(int n)  
  8. {  
  9.     int result = 1;  
  10.     for (int i = 1; i <= n; i++)  
  11.         result *= i;  
  12.     return result;  
  13. }  
  14. void Factorial(int n, int &result)  
  15. {  
  16.     result = 1;  
  17.     for (int i = 1; i <= n; i++)  
  18.         result *= i;  
  19. }  
  20.   
  21. // Returns true iff n is a prime number.  
  22. bool IsPrime(int n)  

抱歉!评论已关闭.