Google Test测试框架自带Sample案例注释翻译

  有一段时间没写博客了,前些时间闲下来看了下google test(gtest)测试框架自带的sample测试样例,感觉还不错,就对里面的注释进行了相关翻译,在此做个标录,对测试流程、方法和设计的理解会有些帮助,方便日后重新查阅,有兴趣的同志不妨看一下

相关说明:

     1、项目工程可到附件中下载

     2、项目工程在visual studio2005环境下编译运行的

     3、对于想对gtest有进一步了解的通知,可参考金山公司一个前辈的gtest技术博客http://www.cnblogs.com/coderzh/archive/2009/03/31/1426758.html(玩转Google开源C++单元测试框架Google Test系列(gtest))

     4、转载请保留该博客地址:http://mzhx-com.iteye.com/

    

正所谓,外行看热闹,内行看门道,在此就不多做解释了,注释和源码相信应该是最好的老师吧

 

工程结构图表:

sample1.h

Cpp代码   收藏代码
  1. //一个用来展示如何应用Google C++测试框架的简单程序示例  
  2.   
  3. #ifndef GTEST_SAMPLES_SAMPLE1_H_  
  4. #define GTEST_SAMPLES_SAMPLE1_H_  
  5.   
  6. // Returns n! (the factorial of n).  For negative n, n! is defined to be 1.  
  7. //返回n!(n的阶乘),对于负数n,n!约定等于1  
  8. int Factorial(int n);  
  9.   
  10. // Returns true iff n is a prime number.  
  11. //如果n是素数返回true  
  12. bool IsPrime(int n);  
  13.   
  14. #endif  // GTEST_SAMPLES_SAMPLE1_H_  

 

sample1.cc

Cpp代码   收藏代码
  1. //一个用来展示如何应用Google C++测试框架的简单程序示例  
  2. #include "stdafx.h"  
  3. #include "sample1.h"  
  4. // Returns n! (the factorial of n).  For negative n, n! is defined to be 1.  
  5. //返回n!(n的阶乘),对于负数n,n!约定等于1  
  6. int Factorial(int n) {  
  7.     int result = 1;  
  8.     for (int i = 1; i <= n; i++) {  
  9.         result *= i;  
  10.     }  
  11.     return result;  
  12. }  
  13. // Returns true iff n is a prime number.  
  14. //如果n是素数返回true  
  15. bool IsPrime(int n) {  
  16.     // Trivial case 1: small numbers  
  17.     //情况1:小于等于1的数字  
  18.     if (n <= 1) return false;  
  19.     // Trivial case 2: even numbers  
  20.     //情况2:整数  
  21.     if (n % 2 == 0) return n == 2;  
  22.     // Now, we have that n is odd and n >= 3.  
  23.     //现在,对于那些大于3的奇数  
  24.     // Try to divide n by every odd number i, starting from 3  
  25.     //从3开始,用每个奇数i去除n  
  26.     for (int i = 3; ; i += 2) {  
  27.         // We only have to try i up to the squre root of n  
  28.         if (i > n/i) break;  
  29.         // Now, we have i <= n/i < n.  
  30.         // If n is divisible by i, n is not prime.  
  31.         if (n % i == 0) return false;  
  32.     }  
  33.     // n has no integer factor in the range (1, n), and thus is prime.  
  34.     return true;  
  35. }  

 

sample1_unittest.cc

Cpp代码   收藏代码
  1. // This sample shows how to write a simple unit test for a function,  
  2. // using Google C++ testing framework.  
  3. //这个示例用来展示如何应用Google C++测试框架来写一个简单的函数测试单元  
  4. // Writing a unit test using Google C++ testing framework is easy as 1-2-3:  
  5. //应用Google C++写一个单元测试很简单,只需要1-2-3共三个步骤  
  6.   
  7.   
  8. // Step 1. Include necessary header files such that the stuff your  
  9. // test logic needs is declared.  
  10. //第一步:引入一些必须的头文件  
  11. // Don't forget gtest.h, which declares the testing framework.  
  12. //不要忘了引入声明测试框架的gtest.h头文件  
  13. #include "stdafx.h"  
  14. #include <limits.h>  
  15. #include "sample1.h"  
  16. #include <gtest/gtest.h>  
  17.   
  18.   
  19. // Step 2. Use the TEST macro to define your tests.  
  20. //第二步:应用TEST宏来定义你的测试  
  21.   
  22. //TEST has two parameters: the test case name and the test name.  
  23. //TEST宏包含两个参数:一个案例【TestCaseName】名,一个测试【TestName】名  
  24.   
  25. // After using the macro, you should define your test logic between a  pair of braces.    
  26. //在应用了宏之后,你应该定义这两者之间的测试逻辑  
  27.   
  28. //You can use a bunch of macros to indicate the success or failure of a test.  
  29. //你应该使用一些宏命令去指出测试是否成功  
  30.   
  31. //EXPECT_TRUE and EXPECT_EQ are  examples of such macros.   
  32. //其中EXPECT_TRUE和EXPECT_EQ就是这样的宏的例子  
  33.   
  34. // For a complete list, see gtest.h.  
  35. //要查看完整的列表,可以去看看gtest.h头文件  
  36.   
  37. // <TechnicalDetails>  
  38. //  
  39. // In Google Test, tests are grouped into test cases.    
  40. //在gtest中,测试都被分组到测试案例中  
  41.   
  42. // This is how we keep test code organized.   
  43. //这就是我们有效组织测试代码的方式  
  44.   
  45. //  You should put logically related tests into the same test case.  
  46. //你应该将这些逻辑上相关的测试应用到相似的测试案例中去  
  47.   
  48. // The test case name and the test name should both be valid C++ identifiers.    
  49. //测试案例名和测试名应该都是有效的C++标识符  
  50.   
  51. // And you should not use underscore (_) in the names.  
  52. //并且你不应该应用强调符号(_)到命名中  
  53.   
  54. // Google Test guarantees that each test you define is run exactly  
  55. // once, but it makes no guarantee on the order the tests are  
  56. // executed.    
  57. //gtest能够保证你定义的每个测试都能准确的运行一次,但是它并不能保证这些测试执行的顺序  
  58.   
  59. //Therefore, you should write your tests in such a way  
  60. // that their results don't depend on their order.  
  61. //所以你应该依输出结果不依赖自身顺序的方式来写这些测试案例  
  62.   
  63. // </TechnicalDetails>  
  64.   
  65.   
  66. // Tests Factorial().  
  67. //测试阶乘函数Factorial().  
  68.   
  69. // Tests factorial of negative numbers.  
  70. //测试传入负数的情况下函数的运行情况  
  71.   
  72. TEST(FactorialTest, Negative) {  
  73.   // This test is named "Negative", and belongs to the "FactorialTest"  
  74.   // test case.  
  75.   //这个测试本身被命名为“Negative”且从属于"FactorialTest"测试案例  
  76.   
  77.   EXPECT_EQ(1, Factorial(-5));  
  78.   EXPECT_EQ(1, Factorial(-1));  
  79.   EXPECT_TRUE(Factorial(-10) > 0);  
  80.   
  81.   // <TechnicalDetails>  
  82.   //<技术细节>  
  83.   
  84.   // EXPECT_EQ(expected, actual) is the same as  
  85.   //  
  86.   //   EXPECT_TRUE((expected) == (actual))  
  87.   //  
  88.   // except that it will print both the expected value and the actual  
  89.   // value when the assertion fails.    
  90.   //EXPECT_EQ(expected, actual)除了在断言失败时会打印出期望值和相应的真实值外,其他的情况都和EXPECT_TRUE((expected) == (actual))相同  
  91.   
  92.   //This is very helpful for debugging.  
  93.   //这对调试来说很有帮助  
  94.   
  95.   //   Therefore in this case EXPECT_EQ is preferred.  
  96.   //因此这样说来EXPECT_EQ是很有用的  
  97.   
  98.   // On the other hand, EXPECT_TRUE accepts any Boolean expression,and is thus more general.  
  99.   // 在另一方面,EXPECT_TRUE会接受任何的Boolean表达式,所以他的用法更普通一些  
  100.   
  101.   //  
  102.   // </TechnicalDetails>  
  103. }  
  104.   
  105. // Tests factorial of 0.  
  106. //使用数字0测试阶乘  
  107.   
  108. TEST(FactorialTest, Zero) {  
  109.   EXPECT_EQ(1, Factorial(0));  
  110. }  
  111.   
  112. // Tests factorial of positive numbers.  
  113. //使用正数测试阶乘  
  114.   
  115. TEST(FactorialTest, Positive) {  
  116.   EXPECT_EQ(1, Factorial(1));  
  117.   EXPECT_EQ(2, Factorial(2));  
  118.   EXPECT_EQ(6, Factorial(3));  
  119.   EXPECT_EQ(40320, Factorial(8));  
  120. }  
  121.   
  122.   
  123. // Tests IsPrime()  
  124. //测试素数检测函数  
  125.   
  126. // Tests negative input.  
  127. //测试负数输入  
  128.   
  129. TEST(IsPrimeTest, Negative) {  
  130.   // This test belongs to the IsPrimeTest test case.  
  131.   //这个测试依赖于IsPrimeTest测试案例  
  132.   
  133.   EXPECT_FALSE(IsPrime(-1));  
  134.   EXPECT_FALSE(IsPrime(-2));  
  135.   EXPECT_FALSE(IsPrime(INT_MIN));  
  136. }  
  137.   
  138. // Tests some trivial cases.  
  139. //测试一些平常的案例  
  140.   
  141. TEST(IsPrimeTest, Trivial) {  
  142.   EXPECT_FALSE(IsPrime(0));  
  143.   EXPECT_FALSE(IsPrime(1));  
  144.   EXPECT_TRUE(IsPrime(2));  
  145.   EXPECT_TRUE(IsPrime(3));  
  146. }  
  147.   
  148. // Tests positive input.  
  149. //测试正数输入  
  150.   
  151. TEST(IsPrimeTest, Positive) {  
  152.   EXPECT_FALSE(IsPrime(4));  
  153.   EXPECT_TRUE(IsPrime(5));  
  154.   EXPECT_FALSE(IsPrime(6));  
  155.   EXPECT_TRUE(IsPrime(23));  
  156. }  
  157.   
  158. // Step 3. Call RUN_ALL_TESTS() in main().  
  159. //第三步:在main()函数中调用 RUN_ALL_TESTS()函数  
  160.   
  161. // We do this by linking in src/gtest_main.cc file, which consists of  
  162. // a main() function which calls RUN_ALL_TESTS() for us.  
  163. //在src/gtest_main.cc文件中有一个调用RUN_ALL_TESTS()函数的main()函数,我们可以引入该文件来实现第三步的要求  
  164.   
  165. // This runs all the tests you've defined, prints the result,   
  166. //在这里可以运行所有你定义的测试,打印输出结果  
  167.   
  168. //and returns 0 if successful, or 1 otherwise.  
  169. //并且如果成功返回0,其他情况返回1  
  170.   
  171. // Did you notice that we didn't register the tests?    
  172. //你有没有发现我们并没有注册这些测试  
  173.   
  174. //The RUN_ALL_TESTS() macro magically knows about all the tests we defined.  
  175. //这个RUN_ALL_TESTS()宏函数能神奇的知道我们定义的所有测试  
  176.   
  177. //Isn't this convenient?  
  178. //这样是不是很方便呢,嘿嘿  

 

sample2.h

Java代码   收藏代码
  1. //一个用来展示如何应用Google C++测试框架的简单程序示例  
  2.   
  3. #ifndef GTEST_SAMPLES_SAMPLE2_H_  
  4. #define GTEST_SAMPLES_SAMPLE2_H_  
  5.   
  6. #include <string.h>  
  7.   
  8.   
  9. // A simple string class.  
  10. //一个简单的string字符串相关类  
  11. class MyString {  
  12. private:  
  13.     const char * c_string_;  
  14.     const MyString& operator=(const MyString& rhs);  
  15.   
  16. public:  
  17.   
  18.     // Clones a 0-terminated C string, allocating memory using new.  
  19.     //克隆一个0结尾的C string字符串,用new关键字分配空间  
  20.     static const char * CloneCString(const char * c_string);  
  21.   
  22.       
  23.     //  
  24.     // C'tors  
  25.   
  26.     // The default c'tor constructs a NULL string.  
  27.     //为c_string_默认赋NULL值的构造函数  
  28.   
  29.     MyString() : c_string_(NULL) {}  
  30.   
  31.     // Constructs a MyString by cloning a 0-terminated C string.  
  32.     explicit MyString(const char * c_string) : c_string_(NULL) {  
  33.         Set(c_string);  
  34.     }  
  35.   
  36.     // Copy c'tor  
  37.     MyString(const MyString& string) : c_string_(NULL) {  
  38.         Set(string.c_string_);  
  39.     }  
  40.   
  41.       
  42.     //  
  43.     // D'tor.  MyString is intended to be a final class, so the d'tor  
  44.     // doesn't need to be virtual.  
  45.     //析构函数:MyString类想定义为final类,所以析构函数没必要定义为virtual  
  46.   
  47.     ~MyString() { delete[] c_string_; }  
  48.   
  49.     // Gets the 0-terminated C string this MyString object represents.  
  50.     //返回MyString对象的c_string_  
  51.     const char * c_string() const { return c_string_; }  
  52.   
  53.     size_t Length() const {  
  54.         return c_string_ == NULL ? 0 : strlen(c_string_);  
  55.     }  
  56.   
  57.     // Sets the 0-terminated C string this MyString object represents.  
  58.     //为MyString对象的c_string赋值  
  59.     void Set(const char * c_string);  
  60. };  
  61.   
  62.   
  63. #endif  // GTEST_SAMPLES_SAMPLE2_H_  

 

sample2.cc

Cpp代码   收藏代码
  1. #include "stdafx.h"  
  2. #include "sample2.h"  
  3.   
  4. #include <string.h>  
  5.   
  6. // Clones a 0-terminated C string, allocating memory using new.  
  7. //克隆复制一个以0结尾的C字符串,用new关键字申请空间  
  8. const char * MyString::CloneCString(const char * c_string) {  
  9.     if (c_string == NULL) return NULL;  
  10.   
  11.     const size_t len = strlen(c_string);  
  12.     char * const clone = new char[ len + 1 ];  
  13.     memcpy(clone, c_string, len + 1);  
  14.   
  15.     return clone;  
  16. }  
  17.   
  18. // Sets the 0-terminated C string this MyString object  
  19. // represents.  
  20. //设置以0结尾的字符串用MyString实体表示  
  21. void MyString::Set(const char * c_string) {  
  22.     // Makes sure this works when c_string == c_string_  
  23.     //确保当c_string == c_string_时这个函数正常工作  
  24.     const char * const temp = MyString::CloneCString(c_string);  
  25.     delete[] c_string_;  
  26.     c_string_ = temp;  
  27. }  

 

 

 

sample2_unittest.cc

Cpp代码   收藏代码
  1. // This sample shows how to write a more complex unit test for a class  
  2. // that has multiple member functions.  
  3. //这个示例用来展示如何为一个拥有多个成员函数的类编写更多复杂的测试单元  
  4.   
  5. // Usually, it's a good idea to have one test for each method in your class.  
  6. //通常,为类中每个方法编写一个测试单元是个不错的想法  
  7.   
  8. //   You don't have to do that exactly, but it helps to keep your tests organized.  
  9. //确切的说你没必要那么做,但是那样会帮助你是你的测试更有条理  
  10.   
  11. //   You may also throw in additional tests as needed.  
  12. // 当然你也可以做些额外的必要的测试。  
  13. #include "stdafx.h"  
  14. #include "sample2.h"  
  15. #include <gtest/gtest.h>  
  16.   
  17. // In this example, we test the MyString class (a simple string).  
  18. //在这个示例中,我们测试MyString类(一个简单的字符串)  
  19.   
  20. // Tests the default c'tor.  
  21. //测试它的默认构造函数  
  22. TEST(MyString, DefaultConstructor) {  
  23.     const MyString s;  
  24.   
  25.     // Asserts that s.c_string() returns NULL.  
  26.     //断言s.c_string()返回NULL  
  27.   
  28.     // <TechnicalDetails>  
  29.     //技术细节  
  30.   
  31.     // If we write NULL instead of  
  32.     //  
  33.     //   static_cast<const char *>(NULL)  
  34.     //  
  35.     // in this assertion, it will generate a warning on gcc 3.4.   
  36.     //如果我们在这个断言中通过写NULL来代替static_cast<const char *>(NULL),那么将得到一个关于gcc3.4的警告  
  37.   
  38.     //The reason is that EXPECT_EQ needs to know the types of its  
  39.     // arguments in order to print them when it fails.    
  40.     //原因是:EXPECT_EQ需要知道它的参数的类型以便在测试失败时打印他们  
  41.   
  42.     //Since NULL is #defined as 0, the compiler will use the formatter function for int to print it  
  43.     //因为NULL被定义为0,所以编译器会用int型的格式化函数来打印他  
  44.   
  45.     //However, gcc thinks that NULL should be used as  
  46.     // a pointer, not an int, and therefore complains.  
  47.     //但是,gcc认为NULL应该被当做指针而不是int型,所以很是抱怨  
  48.   
  49.     // The root of the problem is C++'s lack of distinction between the  
  50.     // integer number 0 and the null pointer constant.    
  51.     //这个问题的的根源是C++中缺少对整数0和null指针常量的区分  
  52.   
  53.     //Unfortunately, we have to live with this fact.  
  54.     //不幸的是,我们必须接受这个事实  
  55.     // </TechnicalDetails>  
  56.     EXPECT_STREQ(NULL, s.c_string());  
  57.   
  58.     EXPECT_EQ(0, s.Length());  
  59. }  
  60.   
  61. const char kHelloString[] = "Hello, world!";  
  62.   
  63. // Tests the c'tor that accepts a C string.  
  64. //测试有一个字符串参数的构造函数  
  65. TEST(MyString, ConstructorFromCString) {  
  66.     const MyString s(kHelloString);  
  67.     EXPECT_TRUE(strcmp(s.c_string(), kHelloString) == 0);  
  68.     EXPECT_EQ(sizeof(kHelloString)/sizeof(kHelloString[0]) - 1,  
  69.         s.Length());  
  70. }  
  71.   
  72. // Tests the copy c'tor.  
  73. //测试拷贝构造函数  
  74. TEST(MyString, CopyConstructor) {  
  75.     const MyString s1(kHelloString);  
  76.     const MyString s2 = s1;  
  77.     EXPECT_TRUE(strcmp(s2.c_string(), kHelloString) == 0);  
  78. }  
  79.   
  80. // Tests the Set method.  
  81. //测试它的Set给字符串赋值的函数  
  82. TEST(MyString, Set) {  
  83.     MyString s;  
  84.   
  85.     s.Set(kHelloString);  
  86.     EXPECT_TRUE(strcmp(s.c_string(), kHelloString) == 0);  
  87.   
  88.     // Set should work when the input pointer is the same as the one  
  89.     // already in the MyString object.  
  90.     //Set函数应该在输入指针和已经在MyString对象中存在的指针一样的情况下也能工作  
  91.     s.Set(s.c_string());  
  92.     EXPECT_TRUE(strcmp(s.c_string(), kHelloString) == 0);  
  93.   
  94.     // Can we set the MyString to NULL?  
  95.     //我们能把MyString设置成NULL吗?  
  96.     s.Set(NULL);  
  97.     EXPECT_STREQ(NULL, s.c_string());  
  98. }  

 

 

 

sample3-inl.h

Cpp代码   收藏代码
  1. //一个用来展示如何应用Google C++测试框架的简单程序示例  
  2.   
  3. #ifndef GTEST_SAMPLES_SAMPLE3_INL_H_  
  4. #define GTEST_SAMPLES_SAMPLE3_INL_H_  
  5.   
  6. #include <stddef.h>  
  7.   
  8.   
  9. // Queue is a simple queue implemented as a singled-linked list.  
  10. //Queue就是一个简单的实现了单向链表功能的队列  
  11. // The element type must support copy constructor.  
  12. //这个元素类型必须支持拷贝构造函数  
  13.   
  14. // E is the element type  
  15. //E是元素类型  
  16. template <typename E>    
  17. class Queue;  
  18.   
  19. // QueueNode is a node in a Queue, which consists of an element of type E and a pointer to the next node.  
  20. //队列节点就是一个在队列中的节点,他由一个元素类型E和指向下一个节点的指针组成  
  21. template <typename E>    
  22. class QueueNode {  
  23.     friend class Queue<E>;  
  24.   
  25. public:  
  26.     // Gets the element in this node.  
  27.     //在一个节点中得到相应的元素  
  28.     const E & element() const { return element_; }  
  29.   
  30.     // Gets the next node in the queue.  
  31.     //在队列中得到下一个节点  
  32.     QueueNode * next() { return next_; }  
  33.     const QueueNode * next() const { return next_; }  
  34.   
  35. private:  
  36.     // Creates a node with a given element value.  The next pointer is set to NULL.  
  37.     // 用一个给定元素值来创建一个节点,它的下一个节点指针被设置成NULL  
  38.     QueueNode(const E & element) : element_(element), next_(NULL) {}  
  39.   
  40.     // We disable the default assignment operator and copy c'tor.  
  41.     //我们将默认的赋值重载运算符和它的拷贝构造函数设置成无效的  
  42.     const QueueNode & operator = (const QueueNode &);  
  43.     QueueNode(const QueueNode &);  
  44.   
  45.     E element_;  
  46.     QueueNode * next_;  
  47. };  
  48.   
  49. template <typename E>    
  50. class Queue {  
  51. public:  
  52.   
  53.     // Creates an empty queue.  
  54.     //创建一个空队列  
  55.     Queue() : head_(NULL), last_(NULL), size_(0) {}  
  56.   
  57.     // D'tor.  Clears the queue.  
  58.     //析构函数,清空队列  
  59.     ~Queue() { Clear(); }  
  60.   
  61.     // Clears the queue.  
  62.     //清空队列函数  
  63.     void Clear() {  
  64.         if (size_ > 0) {  
  65.             // 1. Deletes every node.  
  66.             //1、移除每一个节点  
  67.             QueueNode<E> * node = head_;  
  68.             QueueNode<E> * next = node->next();  
  69.             for (; ;) {  
  70.                 delete node;  
  71.                 node = next;  
  72.                 if (node == NULL) break;  
  73.                 next = node->next();  
  74.             }  
  75.   
  76.             // 2. Resets the member variables.  
  77.             //2、重置成员变量  
  78.             head_ = last_ = NULL;  
  79.             size_ = 0;  
  80.         }  
  81.     }  
  82.   
  83.     // Gets the number of elements.  
  84.     //得到元素的数量  
  85.     size_t Size() const { return size_; }  
  86.   
  87.     // Gets the first element of the queue, or NULL if the queue is empty.、  
  88.     //得到队列的第一个元素,如果队列为空则返回NULL  
  89.     QueueNode<E> * Head() { return head_; }  
  90.     const QueueNode<E> * Head() const { return head_; }  
  91.   
  92.     // Gets the last element of the queue, or NULL if the queue is empty.  
  93.     //得到队列的最后一个元素,如果队列为空则返回NULL  
  94.     QueueNode<E> * Last() { return last_; }  
  95.     const QueueNode<E> * Last() const { return last_; }  
  96.   
  97.     // Adds an element to the end of the queue.  A copy of the element is  
  98.     // created using the copy constructor, and then stored in the queue.  
  99.     // Changes made to the element in the queue doesn't affect the source  
  100.     // object, and vice versa.  
  101.     //添加一个元素到队列的末尾,通过拷贝构造函数创建一个拷贝的元素并将它保存到队列中  
  102.     //在队列中对元素所做的改变不会影响到原对象,反之亦然  
  103.     void Enqueue(const E & element) {  
  104.         QueueNode<E> * new_node = new QueueNode<E>(element);  
  105.   
  106.         if (size_ == 0) {  
  107.             head_ = last_ = new_node;  
  108.             size_ = 1;  
  109.         } else {  
  110.             last_->next_ = new_node;  
  111.             last_ = new_node;  
  112.             size_++;  
  113.         }  
  114.     }  
  115.   
  116.     // Removes the head of the queue and returns it.  Returns NULL if  
  117.     // the queue is empty.  
  118.     //移除队列的头部并且返回他,如果队列为空则返回NULL  
  119.     E * Dequeue() {  
  120.         if (size_ == 0) {  
  121.             return NULL;  
  122.         }  
  123.   
  124.         const QueueNode<E> * const old_head = head_;  
  125.         head_ = head_->next_;  
  126.         size_--;  
  127.         if (size_ == 0) {  
  128.             last_ = NULL;  
  129.         }  
  130.   
  131.         E * element = new E(old_head->element());  
  132.         delete old_head;  
  133.   
  134.         return element;  
  135.     }  
  136.   
  137.     // Applies a function/functor on each element of the queue, and  
  138.     // returns the result in a new queue.  The original queue is not  
  139.     // affected.  
  140.     //根据当前队列复制一个一样的队列,原始队列不会受到影响  
  141.     template <typename F>  
  142.     Queue * Map(F function) const {  
  143.         Queue * new_queue = new Queue();  
  144.         for (const QueueNode<E> * node = head_; node != NULL; node = node->next_) {  
  145.             new_queue->Enqueue(function(node->element()));  
  146.         }  
  147.   
  148.         return new_queue;  
  149.     }  
  150.   
  151. private:  
  152.     QueueNode<E> * head_;  // The first node of the queue.队列的第一个节点  
  153.     QueueNode<E> * last_;  // The last node of the queue.队列的最后一个节点  
  154.     size_t size_;  // The number of elements in the queue.队列中元素的数量  
  155.   
  156.     // We disallow copying a queue.我们不允许通过拷贝得到一个队列  
  157.     Queue(const Queue &);  
  158.     const Queue & operator = (const Queue &);  
  159. };  
  160.   
  161. #endif  // GTEST_SAMPLES_SAMPLE3_INL_H_  

 

sample3_unittest.cc

Cpp代码   收藏代码
  1. // In this example, we use a more advanced feature of Google Test called  
  2. // test fixture.  
  3. //在这个示例中,我们将使用更多的gtest更高级的用法,他叫做“test fixture”(测试夹具)  
  4.   
  5. // A test fixture is a place to hold objects and functions shared by  
  6. // all tests in a test case.    
  7. //一个“test fixture”就是一个用来存放能够被所有的测试和测试案例共享的实例和函数的地方  
  8.   
  9. //Using a test fixture avoids duplicating  
  10. // the test code necessary to initialize and cleanup those common  
  11. // objects for each test.    
  12. //对于那些为每个测试中对初始化或善后处理共同示例所必须的代码来说,使用“test fixture”可以避免重复的复制  
  13.   
  14. //It is also useful for defining sub-routines  
  15. // that your tests need to invoke a lot.  
  16. //  
  17.   
  18. // <TechnicalDetails>  
  19. //  
  20. // The tests share the test fixture in the sense of code sharing, not data sharing.  
  21. //这些测试共享这个“test fixtur”,从意义上来说是共享代码,而不是共享数据  
  22.   
  23. //   Each test is given its own fresh copy of the fixture.  
  24. //每个测试都被赋予一个他自己的关于fixture的最新副本  
  25.   
  26. //   You cannot expect the data modified by one test to be  
  27. // passed on to another test, which is a bad idea.  
  28. //如果你期望通过改变一个测试的数据去影响另一个测试的数据,那么这个想法是一个错误的想法  
  29.   
  30. // The reason for this design is that tests should be independent and repeatable.  
  31. //这样设计的原因是每个测试都应该是独立的且是可重复试验的  
  32.   
  33. //   In particular, a test should not fail as the result of another test's failure.   
  34. //特别要指出的是,一个测试不能因为另一个测试的失败而失败  
  35.   
  36. //  If one test depends on info produced by  
  37. // another test, then the two tests should really be one big test.  
  38. //如果一个测试依赖于另一测试产生的数据,那么着两个测试真的应该设计成是一个测试  
  39.   
  40. // The macros for indicating the success/failure of a test  
  41. // (EXPECT_TRUE, FAIL, etc) need to know what the current test is  
  42. // (when Google Test prints the test result, it tells you which test  
  43. // each failure belongs to).   
  44. //那些可以指明一个测试(EXPECT_TRUE, FAIL等)是否成功的宏命令应该知道当前的测试是什么  
  45. //(当一个gtest打印测试的结果的时候,就是在指出每个失败的结果所对应的测试)  
  46.   
  47. //Technically, these macros invoke a member function of the Test class.  
  48. //从技术上来说,这些宏命令在调用Test 类的一个成员函数  
  49.   
  50. //   Therefore, you cannot use them in a global function.    
  51. // 因此,你不能再全局函数中使用它们,  
  52. //That's why you should put test sub-routines in a test fixture.  
  53. //这就是为什么你应该将测试子程序放到一个“test fixture”中  
  54. // </TechnicalDetails>  
  55. #include "stdafx.h"  
  56. #include <iostream>  
  57. #include "sample3-inl.h"  
  58. #include <gtest/gtest.h>  
  59.  using namespace  std;  
  60.    
  61. // To use a test fixture, derive a class from testing::Test.  
  62. class QueueTestOfTest3 : public testing::Test {  
  63. protected:  // You should make the members protected s.t. they can be  
  64.     // accessed from sub-classes.  
  65.   
  66.     // virtual void SetUp() will be called before each test is run.    
  67.     //virtual void SetUp()会在每个测试运行前被调用  
  68.   
  69.     //You should define it if you need to initialize the varaibles.  
  70.     //如果你想初始化一些变量,那么你应该定义这个函数  
  71.   
  72.     // Otherwise, this can be skipped.  
  73.     //不然,你可以选择跳过这个函数不去实现  
  74.     virtual void SetUp() {  
  75.         cout<<"SetUp()do something"<<endl;  
  76.         q1_.Enqueue(1);  
  77.         q2_.Enqueue(2);  
  78.         q2_.Enqueue(3);  
  79.     }  
  80.   
  81.     // virtual void TearDown() will be called after each test is run.  
  82.     //virtual void TearDown()会在每个测试完了之后被调用  
  83.   
  84.     // You should define it if there is cleanup work to do.   
  85.     //如果你有最后的清理工作要做,你就应该定义这个函数  
  86.   
  87.     //Otherwise, you don't have to provide it.  
  88.     //否则,你没必要提供这个函数实现  
  89.   
  90.     // virtual void TearDown() {  
  91.     // }  
  92.   
  93.     // A helper function that some test uses.  
  94.     //一个一些其他测试会用到的助手函数  
  95.     static int Double(int n) {  
  96.         return 2*n;  
  97.     }  
  98.   
  99.     // A helper function for testing Queue::Map().  
  100.     //一个用来测试Queue::Map().的助手函数  
  101.     void MapTester(const Queue<int> * q) {  
  102.         // Creates a new queue, where each element is twice as big as the corresponding one in q.  
  103.         // 创建一个新的队列queue,它的每一个元素都是位于q中的相似元素的两倍  
  104.         const Queue<int> * const new_q = q->Map(Double);  
  105.   
  106.         // Verifies that the new queue has the same size as q.  
  107.         //验证这个新的队列和队列q的大小一样  
  108.         ASSERT_EQ(q->Size(), new_q->Size());  
  109.   
  110.         // Verifies the relationship between the elements of the two queues.  
  111.         //验证这两个队列之间的关系  
  112.         for ( const QueueNode<int> * n1 = q->Head(), * n2 = new_q->Head();  
  113.             n1 != NULL; n1 = n1->next(), n2 = n2->next() ) {  
  114.                 EXPECT_EQ(2 * n1->element(), n2->element());  
  115.         }  
  116.   
  117.         delete new_q;  
  118.     }  
  119.   
  120.     // Declares the variables your tests want to use.  
  121.     //声明你想要在测试中用到的变量  
  122.     Queue<int> q0_;  
  123.     Queue<int> q1_;  
  124.     Queue<int> q2_;  
  125. };  
  126.   
  127. // When you have a test fixture, you define a test using TEST_F instead of TEST.  
  128. //如果你有一个"test fixture",你应该用TEST_F代替TEST来定义一个测试  
  129.   
  130. // Tests the default c'tor.  
  131. //测试默认构造函数  
  132. TEST_F(QueueTestOfTest3, DefaultConstructor) {  
  133.     // You can access data in the test fixture here.  
  134.     EXPECT_EQ(0, q0_.Size());  
  135. }  
  136.   
  137. // Tests Dequeue().  
  138. //测试出队列  
  139. TEST_F(QueueTestOfTest3, Dequeue) {  
  140.     int * n = q0_.Dequeue();  
  141.     EXPECT_TRUE(n == NULL);  
  142.   
  143.     n = q1_.Dequeue();  
  144.     ASSERT_TRUE(n != NULL);  
  145.     EXPECT_EQ(1, *n);  
  146.     EXPECT_EQ(0, q1_.Size());  
  147.     delete n;  
  148.   
  149.     n = q2_.Dequeue();  
  150.     ASSERT_TRUE(n != NULL);  
  151.     EXPECT_EQ(2, *n);  
  152.     EXPECT_EQ(1, q2_.Size());  
  153.     delete n;  
  154. }  
  155.   
  156. // Tests the Queue::Map() function.  
  157. //测试Queue::Map() 函数  
  158. TEST_F(QueueTestOfTest3, Map) {  
  159.     MapTester(&q0_);  
  160.     MapTester(&q1_);  
  161.     MapTester(&q2_);  
  162. }  

 

sample4.h

Cpp代码   收藏代码
  1. #ifndef GTEST_SAMPLES_SAMPLE4_H_  
  2. #define GTEST_SAMPLES_SAMPLE4_H_  
  3.   
  4. // A simple monotonic counter.  
  5. //一个很简单单调的计数器  
  6. class Counter {  
  7. private:  
  8.     int counter_;  
  9.   
  10. public:  
  11.     // Creates a counter that starts at 0.  
  12.     //创建一个起始值为0的计数器  
  13.     Counter() : counter_(0) {}  
  14.   
  15.     // Returns the current counter value, and increments it.  
  16.     //返回当前的计数值,并且使他自增一  
  17.     int Increment();  
  18.   
  19.     // Prints the current counter value to STDOUT.  
  20.     //采用标准输出打印当前的计数值  
  21.     void Print() const;  
  22. };  
  23.   
  24. #endif  // GTEST_SAMPLES_SAMPLE4_H_  

 

sample4.cc

Cpp代码   收藏代码
  1. #include <stdio.h>  
  2. #include "stdafx.h"  
  3. #include "sample4.h"  
  4.   
  5. // Returns the current counter value, and increments it.  
  6. //返回当前的计数值,并且使他自增一  
  7. int Counter::Increment() {  
  8.   return counter_++;  
  9. }  
  10.   
  11. // Prints the current counter value to STDOUT.  
  12. //采用标准输出打印当前的计数值  
  13. void Counter::Print() const {  
  14.   printf("%d", counter_);  
  15. }  

 

 

 

 

 

 

sample4_unittest.cc

Cpp代码   收藏代码
  1. #include "stdafx.h"  
  2. #include <gtest/gtest.h>  
  3. #include "sample4.h"  
  4.   
  5. // Tests the Increment() method.  
  6. //测试计数器类的Increment()函数  
  7. TEST(Counter, Increment) {  
  8.     Counter c;  
  9.   
  10.     // EXPECT_EQ() evaluates its arguments exactly once, so they can have side effects.  
  11.     // EXPECT_EQ()准确的评估他的参数一次,所以他们会有副作用  
  12.   
  13.     EXPECT_EQ(0, c.Increment());  
  14.     EXPECT_EQ(1, c.Increment());  
  15.     EXPECT_EQ(2, c.Increment());  
  16. }  

 

prime_tables.h

Cpp代码   收藏代码
  1. // This provides interface PrimeTable that determines whether a number is a  
  2. // prime and determines a next prime number.  
  3. //这里提供了一个接口类PrimeTable,他可以确定一个数字是否是素数并且确定下一个素数数字  
  4.   
  5. //This interface is used  
  6. // in Google Test samples demonstrating use of parameterized tests.  
  7. //这个接口已经被应用于gtest用来展示参数化测试的示例中了  
  8.   
  9. #ifndef GTEST_SAMPLES_PRIME_TABLES_H_  
  10. #define GTEST_SAMPLES_PRIME_TABLES_H_  
  11. //#include "stdafx.h"  
  12. #include <algorithm>  
  13.   
  14. // The prime table interface.  
  15. //素数表接口  
  16. class PrimeTable {  
  17.  public:  
  18.   virtual ~PrimeTable() {}  
  19.   
  20.   // Returns true iff n is a prime number.  
  21.   //返回true如果n是一个素数  
  22.   virtual bool IsPrime(int n) const = 0;  
  23.   
  24.   // Returns the smallest prime number greater than p; or returns -1  
  25.   // if the next prime is beyond the capacity of the table.  
  26.   //返回比p大的所有素数中最小的那一个数,或者如果下一个素数超出表的容量时返回-1  
  27.   
  28.   virtual int GetNextPrime(int p) const = 0;  
  29. };  
  30.   
  31. // Implementation #1 calculates the primes on-the-fly.  
  32. //一个实现类,用来计算素数  
  33. class OnTheFlyPrimeTable : public PrimeTable {  
  34. public:  
  35.     virtual bool IsPrime(int n) const   
  36.     {  
  37.         if (n <= 1) return false;  
  38.   
  39.         for (int i = 2; i*i <= n; i++) {  
  40.             // n is divisible by an integer other than 1 and itself.  
  41.             //n能够被除1和他自身以外的整数相除  
  42.             if ((n % i) == 0) return false;  
  43.         }  
  44.   
  45.         return true;  
  46.     }  
  47.   
  48.   virtual int GetNextPrime(int p) const {  
  49.     for (int n = p + 1; n > 0; n++) {  
  50.       if (IsPrime(n)) return n;  
  51.     }  
  52.   
  53.     return -1;  
  54.   }  
  55. };  
  56.   
  57. // Implementation #2 pre-calculates the primes and stores the result  
  58. // in an array.  
  59. //第二个实现:预先计算出素数然后将这些结果存放到一个数组中  
  60.   
  61. class PreCalculatedPrimeTable : public PrimeTable {  
  62. public:  
  63.     // 'max' specifies the maximum number the prime table holds.  
  64.     explicit PreCalculatedPrimeTable(int max)  
  65.         : is_prime_size_(max + 1), is_prime_(new bool[max + 1]) {  
  66.             CalculatePrimesUpTo(max);  
  67.     }  
  68.     virtual ~PreCalculatedPrimeTable() { delete[] is_prime_; }  
  69.   
  70.     virtual bool IsPrime(int n) const {  
  71.         return 0 <= n && n < is_prime_size_ && is_prime_[n];  
  72.     }  
  73.   
  74.     virtual int GetNextPrime(int p) const {  
  75.         for (int n = p + 1; n < is_prime_size_; n++) {  
  76.             if (is_prime_[n]) return n;  
  77.         }  
  78.   
  79.         return -1;  
  80.     }  
  81.   
  82. private:  
  83.     void CalculatePrimesUpTo(int max) {  
  84.         ::std::fill(is_prime_, is_prime_ + is_prime_size_, true);  
  85.         is_prime_[0] = is_prime_[1] = false;  
  86.   
  87.         for (int i = 2; i <= max; i++) {  
  88.             if (!is_prime_[i]) continue;  
  89.   
  90.             // Marks all multiples of i (except i itself) as non-prime.  
  91.             //标记所有的i的倍数(不包括i自身)不是素数  
  92.             for (int j = 2*i; j <= max; j += i) {  
  93.                 is_prime_[j] = false;  
  94.             }  
  95.         }  
  96.     }  
  97.   
  98.     const int is_prime_size_;  
  99.     boolconst is_prime_;  
  100. };  
  101.   
  102. #endif  // GTEST_SAMPLES_PRIME_TABLES_H_  

 

sample5_unittest.cc

Cpp代码   收藏代码
  1. // This sample teaches how to reuse a test fixture in multiple test  
  2. // cases by deriving sub-fixtures from it.  
  3. //这个示例教给大家怎么通过子fixtrues在一个多重的测试案例中重复使用一个“test fixture”  
  4.   
  5. // When you define a test fixture, you specify the name of the test  
  6. // case that will use this fixture.    
  7. //当你定义一个test fixture的时候,有要指定要用到该fixture的测试案例的名称  
  8.   
  9. //Therefore, a test fixture can be used by only one test case.  
  10. //所以,一个test fixtrue只能够被咦一个测试案例使用  
  11.   
  12. // Sometimes, more than one test cases may want to use the same or slightly different test fixtures  
  13. //有时候,也许更多的测试案例想使用一个相同或者只有少许差别的test fixtures  
  14.   
  15. //For example, you may want to  
  16. // make sure that all tests for a GUI library don't leak important  
  17. // system resources like fonts and brushes.  
  18. //举例来说,你也许想确保所有针对GUI库的测试不会漏掉那些比如字体和笔刷之类的重要的系统资源  
  19.   
  20. //In Google Test, you do  
  21. // this by putting the shared logic in a super (as in "super class")  
  22. // test fixture,   
  23. //在gtest中,你想要实现这个可以通过把那些共同逻辑放入一个超级的test fixture中  
  24.   
  25. //and then have each test case use a fixture derived  
  26. // from this super fixture.  
  27. //并且可以通过从超级test fixture派生来得到每个测试案例所需的fixture  
  28. #include "stdafx.h"  
  29. #include <limits.h>  
  30. #include <time.h>  
  31. #include "sample3-inl.h"  
  32. #include <gtest/gtest.h>  
  33. #include "sample1.h"  
  34.   
  35. // In this sample, we want to ensure that every test finishes within ~5 seconds.  
  36. //在这个示例中,我们想保证每个测试都在5秒钟之内完成  
  37.   
  38. //   If a test takes longer to run, we consider it a failure.  
  39. // 如果一个测试需要消耗跟多的时间去运行,那么我们认为这是测试的结果是失败的  
  40.   
  41.   
  42. // We put the code for timing a test in a test fixture called "QuickTest".   
  43. //我们将给一个测试计时的代码放入一个被称作“QuickTest”的test fixture中  
  44.   
  45. // QuickTest is intended to be the super fixture that other fixtures derive from  
  46. //QuickTest被设计成其他子fixtures可以用来派生的超级fixture  
  47.   
  48. // therefore there is no test case with  
  49. // the name "QuickTest".  This is OK.  
  50. //所以,这里没有命名为“QuickTest”的测试案例,这样就可以了  
  51.   
  52. // Later, we will derive multiple test fixtures from QuickTest.  
  53. //稍后我们会从QuickTest派生一些text fixtures  
  54.   
  55. class QuickTest : public testing::Test {  
  56. protected:  
  57.     // Remember that SetUp() is run immediately before a test starts.  
  58.     //要记住,SetUp() 函数会在一个测试起始前立刻执行  
  59.   
  60.     // This is a good place to record the start time.  
  61.     //这是一个用来记录起始时间的好地方  
  62.   
  63.     virtual void SetUp() {  
  64.         start_time_ = time(NULL);  
  65.     }  
  66.   
  67.     // TearDown() is invoked immediately after a test finishes.    
  68.     // TearDown()会在一个测试结束后被立即调用  
  69.   
  70.     //Here we check if the test was too slow.  
  71.     //在这里我们可以检测者个测试是不是很慢  
  72.   
  73.     virtual void TearDown() {  
  74.         // Gets the time when the test finishes  
  75.         //取得测试结束时的时间  
  76.         const time_t end_time = time(NULL);  
  77.   
  78.         // Asserts that the test took no more than ~5 seconds.    
  79.         //断言这个测试花费的时间没有超过5分钟  
  80.   
  81.         //Did you know that you can use assertions in SetUp() and TearDown() as well?  
  82.         // 你是否知道我们也可以同样在SetUp()函数中使用断言呢?  
  83.   
  84.         EXPECT_TRUE(end_time - start_time_ <= 5) << "The test took too long.";  
  85.     }  
  86.   
  87.     // The UTC time (in seconds) when the test starts  
  88.     //当测试启动时的UTC时间(以秒计)  
  89.   
  90.     time_t start_time_;  
  91. };  
  92.   
  93.   
  94. // We derive a fixture named IntegerFunctionTest from the QuickTest fixture.  
  95. //我们从QuickTest派生一个名叫“IntegerFunctionTest”的fixture  
  96.   
  97. //   All tests using this fixture will be automatically required to be quick.  
  98. // 所有的使用这个fixture的测试都会无意识的被要求运行的很快  
  99. class IntegerFunctionTest : public QuickTest {  
  100.     // We don't need any more logic than already in the QuickTest fixture.  
  101.     //我们不需要比那些已经存在于QuickTest的更多的处理逻辑  
  102.   
  103.     // Therefore the body is empty.  
  104.     //所以该类中的内容是空的  
  105. };  
  106.   
  107.   
  108. // Now we can write tests in the IntegerFunctionTest test case.  
  109. //现在我们可以在IntegerFunctionTest测试案例中去写一些测试  
  110.   
  111. // Tests Factorial()  
  112. //测试计算阶乘的函数Factorial()  
  113.   
  114. TEST_F(IntegerFunctionTest, Factorial) {  
  115.     // Tests factorial of negative numbers.  
  116.     EXPECT_EQ(1, Factorial(-5));  
  117.     EXPECT_EQ(1, Factorial(-1));  
  118.     EXPECT_TRUE(Factorial(-10) > 0);  
  119.   
  120.     // Tests factorial of 0.  
  121.     EXPECT_EQ(1, Factorial(0));  
  122.   
  123.     // Tests factorial of positive numbers.  
  124.     EXPECT_EQ(1, Factorial(1));  
  125.     EXPECT_EQ(2, Factorial(2));  
  126.     EXPECT_EQ(6, Factorial(3));  
  127.     EXPECT_EQ(40320, Factorial(8));  
  128. }  
  129.   
  130.   
  131. // Tests IsPrime()  
  132. //测试检测一个数是否为素数的函数IsPrime()  
  133. TEST_F(IntegerFunctionTest, IsPrime) {  
  134.     // Tests negative input.  
  135.     EXPECT_TRUE(!IsPrime(-1));  
  136.     EXPECT_TRUE(!IsPrime(-2));  
  137.     EXPECT_TRUE(!IsPrime(INT_MIN));  
  138.   
  139.     // Tests some trivial cases.  
  140.     EXPECT_TRUE(!IsPrime(0));  
  141.     EXPECT_TRUE(!IsPrime(1));  
  142.     EXPECT_TRUE(IsPrime(2));  
  143.     EXPECT_TRUE(IsPrime(3));  
  144.   
  145.     // Tests positive input.  
  146.     EXPECT_TRUE(!IsPrime(4));  
  147.     EXPECT_TRUE(IsPrime(5));  
  148.     EXPECT_TRUE(!IsPrime(6));  
  149.     EXPECT_TRUE(IsPrime(23));  
  150. }  
  151.   
  152.   
  153. // The next test case (named "QueueTest") also needs to be quick, so  
  154. // we derive another fixture from QuickTest.  
  155. //接下来的测试案例(命名为“QueueTest”)也需要快速运行,所以我们从QuickTest  
  156. //派生了另外一个fixture  
  157.   
  158. // The QueueTest test fixture has some logic and shared objects in addition to what's in QuickTest already.  
  159. //QueueTest测试有一些自己的逻辑和那些已经在QuickTest存在的共享的对象  
  160.   
  161. //   We define the additional  
  162. // stuff inside the body of the test fixture, as usual.  
  163. //通常我们在这个测试fixture的内部定义一些额外的东西  
  164.   
  165. class QueueTest : public QuickTest {  
  166. protected:  
  167.     virtual void SetUp() {  
  168.         // First, we need to set up the super fixture (QuickTest).  
  169.         //首先,我们需要配置超级fixture(QuickTest)  
  170.         QuickTest::SetUp();  
  171.   
  172.         // Second, some additional setup for this fixture.  
  173.         //第二,设置一些和这个fixture相关的额外的东西  
  174.         q1_.Enqueue(1);  
  175.         q2_.Enqueue(2);  
  176.         q2_.Enqueue(3);  
  177.     }  
  178.   
  179.     // By default, TearDown() inherits the behavior of QuickTest::TearDown().  
  180.     //默认情况下,TearDown()函数会从QuickTest的TearDown()函数中继承相关的逻辑行为  
  181.     //   As we have no additional cleaning work  
  182.     // for QueueTest, we omit it here.  
  183.     //考虑到我们没有为QueueTest追加设计更多的清理工作逻辑,我们可以在这里忽略它  
  184.     // virtual void TearDown() {  
  185.     //   QuickTest::TearDown();  
  186.     // }  
  187.   
  188.     Queue<int> q0_;  
  189.     Queue<int> q1_;  
  190.     Queue<int> q2_;  
  191. };  
  192.   
  193.   
  194. // Now, let's write tests using the QueueTest fixture.  
  195. //现在,我们使用QueueTest 来写我们的测试  
  196.   
  197. // Tests the default constructor.  
  198. //测试默认构造函数  
  199.   
  200. TEST_F(QueueTest, DefaultConstructor) {  
  201.     EXPECT_EQ(0, q0_.Size());  
  202. }  
  203.   
  204. // Tests Dequeue().  
  205. //测试队列弹出函数Dequeue()  
  206.   
  207. TEST_F(QueueTest, Dequeue) {  
  208.     int * n = q0_.Dequeue();  
  209.     EXPECT_TRUE(n == NULL);  
  210.   
  211.     n = q1_.Dequeue();  
  212.     EXPECT_TRUE(n != NULL);  
  213.     EXPECT_EQ(1, *n);  
  214.     EXPECT_EQ(0, q1_.Size());  
  215.     delete n;  
  216.   
  217.     n = q2_.Dequeue();  
  218.     EXPECT_TRUE(n != NULL);  
  219.     EXPECT_EQ(2, *n);  
  220.     EXPECT_EQ(1, q2_.Size());  
  221.     delete n;  
  222. }  
  223.   
  224. // If necessary, you can derive further test fixtures from a derived fixture itself.  
  225. // 如果有必要你可以从已经派生了的fixture自身派生更深层次的test fixture  
  226.   
  227. // For example, you can derive another fixture from QueueTest.  
  228. //举例来说,你可以从QueueTest派生另外一个fixture  
  229. //   Google Test imposes no limit on how deep the hierarchy can be.  
  230. //gtest没有对能够派生的层次的深度做限制  
  231. //   In practice, however, you probably don't want it to be too deep as to be confusing.  
  232. // 但是在实践中,你或许因为怕犯迷糊而不愿意把他的层次搞得太深  

 

sample6_unittest.cc

Cpp代码   收藏代码
  1. // This sample shows how to test common properties of multiple  
  2. // implementations of the same interface (aka interface tests).  
  3. //这个示例用来展示如何去测试多个实现了相同接口(类)的共同属性(又叫做接口测试)  
  4.   
  5. // The interface and its implementations are in this header.  
  6. //接口和他的几个相应实现都在这个头部中  
  7. #include "stdafx.h"  
  8. #include "prime_tables.h"  
  9. #include <gtest/gtest.h>  
  10.   
  11. // First, we define some factory functions for creating instances of the implementations.  
  12. //首先,我们为了创建一些实现了接口的类的实例要去定义一些工厂方法  
  13.   
  14. //   You may be able to skip this step if all your  
  15. // implementations can be constructed the same way.  
  16. //如果你的所有接口实现能够以一种方式组织,那么你就可以跳过这一步  
  17.   
  18. template <class T>  
  19. PrimeTable* CreatePrimeTable();  
  20.   
  21. template <>  
  22. PrimeTable* CreatePrimeTable<OnTheFlyPrimeTable>() {  
  23.     return new OnTheFlyPrimeTable;  
  24. }  
  25.   
  26. template <>  
  27. PrimeTable* CreatePrimeTable<PreCalculatedPrimeTable>() {  
  28.     return new PreCalculatedPrimeTable(10000);  
  29. }  
  30.   
  31. // Then we define a test fixture class template.  
  32. //接下来我们定义一个test fixture的模版类  
  33.   
  34. template <class T>  
  35. class PrimeTableTest : public testing::Test {  
  36. protected:  
  37.     // The ctor calls the factory function to create a prime table  
  38.     // implemented by T.  
  39.     //构造函数调用工厂方法通过泛型T创建一个素数表  
  40.     PrimeTableTest() : table_(CreatePrimeTable<T>()) {}  
  41.   
  42.     virtual ~PrimeTableTest() { delete table_; }  
  43.   
  44.     // Note that we test an implementation via the base interface instead of the actual implementation class.  
  45.     //需要注意的是,我们是通过接口而不是他的实现类来测试一个实现的  
  46.   
  47.     //   This is important for keeping the tests close to the real world scenario,  
  48.     //  where the implementation is invoked via the base interface.   
  49.     //在那些通过接口来调用实现类的地方,保持测试接近现实世界场景是很重要的  
  50.   
  51.     //  It avoids got-yas where the implementation class has a method that shadows  
  52.     // a method with the same name (but slightly different argument  
  53.     // types) in the base interface, for example.  
  54.     // 举例来说,在那些实现类中有一个方法名覆盖接口中另一个方法名  
  55.     PrimeTable* const table_;  
  56. };  
  57.   
  58. #if GTEST_HAS_TYPED_TEST  
  59.   
  60. using testing::Types;  
  61.   
  62. // Google Test offers two ways for reusing tests for different types.  
  63. //gtest 提供了两个方法可以针对不同的类型重复利用一些测试  
  64.   
  65. // The first is called "typed tests".   
  66. //第一个方法被称作类型测试(typed test)  
  67.   
  68. //You should use it if you  
  69. // already know *all* the types you are gonna exercise when you write  
  70. // the tests.  
  71. //如果当你写一个测试的时候已经知道了在你的练习中将要用到的所有类型,那么你应该使用这个方法  
  72.   
  73. // To write a typed test case, first use  
  74. //  
  75. //   TYPED_TEST_CASE(TestCaseName, TypeList);  
  76. //  
  77. // to declare it and specify the type parameters.   
  78. //想要写一个类型测试案例,首先应该使用TYPED_TEST_CASE(TestCaseName, TypeList)去声明并且制定类型参数  
  79.   
  80. //As with TEST_F, TestCaseName must match the test fixture name.  
  81. //正如TEST_F一样,测试案例名字必须和test fixture的名字一致  
  82.   
  83. // The list of types we want to test.  
  84. //我们想要测试的参数列表  
  85. typedef Types<OnTheFlyPrimeTable, PreCalculatedPrimeTable> Implementations;  
  86.   
  87. TYPED_TEST_CASE(PrimeTableTest, Implementations);  
  88.   
  89. // Then use TYPED_TEST(TestCaseName, TestName) to define a typed test,  
  90. // similar to TEST_F.  
  91. //接下来我们像定义TEST_F一样使用TYPED_TEST(TestCaseName, TestName)去定义一个类型测试  
  92.   
  93. TYPED_TEST(PrimeTableTest, ReturnsFalseForNonPrimes) {  
  94.     // Inside the test body, you can refer to the type parameter by  
  95.     // TypeParam, and refer to the fixture class by TestFixture.   
  96.     //在测试体中,你可以通过TypeParam指定类型参数,通过TestFixture指定fixture  
  97.   
  98.     // We don't need them in this example.  
  99.     //在这个例子中我们不需要他们  
  100.     // Since we are in the template world, C++ requires explicitly  
  101.     // writing 'this->' when referring to members of the fixture class.  
  102.     //因为我们都在模版世界之中,在指明fixture类的成员的时候,C++明确要求写'this->'  
  103.   
  104.     // This is something you have to learn to live with.  
  105.     //这就是一些你必须要学会的  
  106.     EXPECT_FALSE(this->table_->IsPrime(-5));  
  107.     EXPECT_FALSE(this->table_->IsPrime(0));  
  108.     EXPECT_FALSE(this->table_->IsPrime(1));  
  109.     EXPECT_FALSE(this->table_->IsPrime(4));  
  110.     EXPECT_FALSE(this->table_->IsPrime(6));  
  111.     EXPECT_FALSE(this->table_->IsPrime(100));  
  112. }  
  113.   
  114. TYPED_TEST(PrimeTableTest, ReturnsTrueForPrimes) {  
  115.     EXPECT_TRUE(this->table_->IsPrime(2));  
  116.     EXPECT_TRUE(this->table_->IsPrime(3));  
  117.     EXPECT_TRUE(this->table_->IsPrime(5));  
  118.     EXPECT_TRUE(this->table_->IsPrime(7));  
  119.     EXPECT_TRUE(this->table_->IsPrime(11));  
  120.     EXPECT_TRUE(this->table_->IsPrime(131));  
  121. }  
  122.   
  123. TYPED_TEST(PrimeTableTest, CanGetNextPrime) {  
  124.     EXPECT_EQ(2, this->table_->GetNextPrime(0));  
  125.     EXPECT_EQ(3, this->table_->GetNextPrime(2));  
  126.     EXPECT_EQ(5, this->table_->GetNextPrime(3));  
  127.     EXPECT_EQ(7, this->table_->GetNextPrime(5));  
  128.     EXPECT_EQ(11, this->table_->GetNextPrime(7));  
  129.     EXPECT_EQ(131, this->table_->GetNextPrime(128));  
  130. }  
  131.   
  132. // That's it!  Google Test will repeat each TYPED_TEST for each type  
  133. // in the type list specified in TYPED_TEST_CASE.    
  134. //就是这样,gtest 将会为在TYPED_TEST_CASE指定的类型列表中的每个类型重复一次TYPED_TEST  
  135.   
  136. //Sit back and be happy that you don't have to define them multiple times.  
  137. //你不必重复多次地定义他们,你可以感到放松和高兴  
  138.   
  139. #endif  // GTEST_HAS_TYPED_TEST  
  140.   
  141. #if GTEST_HAS_TYPED_TEST_P  
  142.   
  143. using testing::Types;  
  144.   
  145. // Sometimes, however, you don't yet know all the types that you want  
  146. // to test when you write the tests.    
  147. //然而,有时候当你写测试的时候你也许还不全知道你想测试的所有类型  
  148.   
  149. //For example, if you are the author of an interface and expect other people to implement it  
  150. //举例来说,如果你是接口的定义者并且你希望其他的人来实现它  
  151.   
  152. //you might want to write a set of tests to make sure each implementation conforms to some basic requirements ,  
  153. //那么你可能想去写一系列的测试去保证每个实现都遵循一些基本要求  
  154.   
  155. // but you don't know what implementations will be written in the future.  
  156. // 但是将来你并不知道那些实现都写了些什么  
  157.   
  158. // How can you write the tests without committing to the type parameters?  
  159. //如果没有致力于这些类型参数那么你该怎么来写这些测试呢  
  160.   
  161. //  That's what "type-parameterized tests" can do for you.  
  162. //那就是"type-parameterized tests"(类型参数化测试)能为你做的  
  163.   
  164. // It is a bit more involved than typed tests  
  165. //他要比类型测试有点复杂  
  166.   
  167. //but in return you get a  
  168. // test pattern that can be reused in many contexts, which is a big win.  
  169. //但是反过来你可以得到一个可以在许多情况下重复利用的测试模式,这就是一个收获  
  170.   
  171. //Here's how you do it:  
  172. //这里讲你怎么来做:  
  173.   
  174. // First, define a test fixture class template.  
  175. //首先,定义一个test fixture的模版类  
  176.   
  177. //Here we just reuse the PrimeTableTest fixture defined earlier:  
  178. //在这里我们重复利用了已经早定义过的PrimeTableTest fixture  
  179.   
  180. template <class T>  
  181. class PrimeTableTest2 : public PrimeTableTest<T> {  
  182. };  
  183.   
  184. // Then, declare the test case.    
  185. //接下来,声明这个测试案例  
  186.   
  187. //The argument is the name of the test fixture, and also the name of the test case (as usual).  
  188. // 参数是这个test fixture的名字,也是测试用例的名字(像平常一样)  
  189.   
  190. //The _P suffix is for "parameterized" or "pattern".  
  191. //这个_P后缀是为了支持“parameterized”(参数化)或者“pattern”(模式)  
  192. TYPED_TEST_CASE_P(PrimeTableTest2);  
  193.   
  194. // Next, use TYPED_TEST_P(TestCaseName, TestName) to define a test,  
  195. // similar to what you do with TEST_F.  
  196. //下一步,像你对待TEST_F一样,使用 TYPED_TEST_P(TestCaseName, TestName)来定义你的测试  
  197.   
  198. TYPED_TEST_P(PrimeTableTest2, ReturnsFalseForNonPrimes) {  
  199.     EXPECT_FALSE(this->table_->IsPrime(-5));  
  200.     EXPECT_FALSE(this->table_->IsPrime(0));  
  201.     EXPECT_FALSE(this->table_->IsPrime(1));  
  202.     EXPECT_FALSE(this->table_->IsPrime(4));  
  203.     EXPECT_FALSE(this->table_->IsPrime(6));  
  204.     EXPECT_FALSE(this->table_->IsPrime(100));  
  205. }  
  206.   
  207. TYPED_TEST_P(PrimeTableTest2, ReturnsTrueForPrimes) {  
  208.     EXPECT_TRUE(this->table_->IsPrime(2));  
  209.     EXPECT_TRUE(this->table_->IsPrime(3));  
  210.     EXPECT_TRUE(this->table_->IsPrime(5));  
  211.     EXPECT_TRUE(this->table_->IsPrime(7));  
  212.     EXPECT_TRUE(this->table_->IsPrime(11));  
  213.     EXPECT_TRUE(this->table_->IsPrime(131));  
  214. }  
  215.   
  216. TYPED_TEST_P(PrimeTableTest2, CanGetNextPrime) {  
  217.     EXPECT_EQ(2, this->table_->GetNextPrime(0));  
  218.     EXPECT_EQ(3, this->table_->GetNextPrime(2));  
  219.     EXPECT_EQ(5, this->table_->GetNextPrime(3));  
  220.     EXPECT_EQ(7, this->table_->GetNextPrime(5));  
  221.     EXPECT_EQ(11, this->table_->GetNextPrime(7));  
  222.     EXPECT_EQ(131, this->table_->GetNextPrime(128));  
  223. }  
  224.   
  225. // Type-parameterized tests involve one extra step: you have to  
  226. // enumerate the tests you defined:  
  227. //类型参数化测试涉及到一个额外的步骤:你必须要枚举你所定义的测试  
  228.   
  229. REGISTER_TYPED_TEST_CASE_P(  
  230.                            PrimeTableTest2,  // The first argument is the test case name.//第一个参数是测试案例名  
  231.                            // The rest of the arguments are the test names.//其他的是测试名  
  232.                            ReturnsFalseForNonPrimes, ReturnsTrueForPrimes, CanGetNextPrime);  
  233.   
  234. // At this point the test pattern is done.    
  235. //这时候测试模式已经完备了  
  236.   
  237. //However, you don't have any real test yet as you haven't said which types you want to run the tests with.  
  238. // 然而,你还没有任何真实的测试,因为你还没有指出使用哪些类型来运行这些测试  
  239.   
  240. // To turn the abstract test pattern into real tests, you instantiate it with a list of types.  
  241. //为了将这些抽象测试变成真实的测试,你需要用一系列的类型来实例化他  
  242.   
  243. //   Usually the test pattern will be defined in a .h file,  
  244. //通常,这个测试模式会被定义到一个a.h头文件中  
  245.   
  246. //  and anyone can #include and instantiate it.    
  247. //并且任何地方都可以通过#include来示例化他  
  248.   
  249. //You can even instantiate it more than once in the same program.   
  250. //你甚至可以在同一个程序中不止一次的实例化他  
  251.   
  252. //To tell different instances apart, you give each of them a name,   
  253. //为了区分开实例,你要给每个一个名字  
  254.   
  255. //which will become part of the test case name and can be used in test filters.  
  256. //这些名字将会成为测试案例的一部分并且会被应用到测试过滤中  
  257.   
  258. // The list of types we want to test.    
  259. //下面是要测试的类型列表  
  260. //Note that it doesn't have to be defined at the time we write the TYPED_TEST_P()s.  
  261. //需要指出的是你在要写TYPED_TEST_P()s时没必要定义这些(参数列表)  
  262. typedef Types<OnTheFlyPrimeTable, PreCalculatedPrimeTable>  
  263. PrimeTableImplementations;  
  264. INSTANTIATE_TYPED_TEST_CASE_P(OnTheFlyAndPreCalculated,    // Instance name示例名  
  265.                               PrimeTableTest2,             // Test case name测试案例名  
  266.                               PrimeTableImplementations);  // Type list类型参数  
  267.   
  268. #endif  // GTEST_HAS_TYPED_TEST_P  

 

sample7_unittest.cc

Cpp代码   收藏代码
  1. // This sample shows how to test common properties of multiple  
  2. // implementations of an interface (aka interface tests) using  
  3. // value-parameterized tests.   
  4. //这个示例用来展示如何使用值参数测试法去测试多个实现了相同接口(类)的共同属性(又叫做接口测试)  
  5.   
  6. //Each test in the test case has  
  7. // a parameter that is an interface pointer to an implementation tested.  
  8. // 每个在测试案例中的测试都有一个参数,这个参数是一个指针并且指向已经实现的测试  
  9.   
  10. // The interface and its implementations are in this header.  
  11. //这些接口和它的相关实现都在这个头文件中  
  12. #include "stdafx.h"  
  13. #include "prime_tables.h"  
  14. #include <gtest/gtest.h>  
  15.   
  16. #if GTEST_HAS_PARAM_TEST  
  17.   
  18. using ::testing::TestWithParam;  
  19. using ::testing::Values;  
  20.   
  21. // As a general rule, tested objects should not be reused between tests.  
  22. //按照通常的惯例,已经被测试过的实体不应该在多个测试之间重复利用  
  23.   
  24. // Also, their constructors and destructors of tested objects can have side effects  
  25. //另外测试实体的构造函数和析构函数会有副作用  
  26.   
  27. //Thus you should create and destroy them for each test.  
  28. //所以你应该为每个测试创建并销毁他们  
  29.   
  30. // In this sample we will define a simple factory function for PrimeTable objects.   
  31. //在这个例子中我们将为PrimeTable实体定义一个简单的工厂方法  
  32.   
  33. // We will instantiate objects in test's SetUp() method and delete them in TearDown() method.  
  34. // 我们将在测试的SetUp()方法中实例化实体并且在TearDown()中删除他们  
  35. typedef PrimeTable* CreatePrimeTableFunc();  
  36.   
  37. PrimeTable* CreateOnTheFlyPrimeTable() {  
  38.     return new OnTheFlyPrimeTable();  
  39. }  
  40.   
  41. template <size_t max_precalculated>  
  42. PrimeTable* CreatePreCalculatedPrimeTable() {  
  43.     return new PreCalculatedPrimeTable(max_precalculated);  
  44. }  
  45.   
  46. // Inside the test body, fixture constructor, SetUp(), and TearDown()  
  47. // you can refer to the test parameter by GetParam().  
  48. //在测试体、fixture的构造函数、 SetUp(), 和 TearDown()里,你可以通过GetParam()函数来指向测试参数  
  49.   
  50. // In this case, the test parameter is a PrimeTableFactory interface pointer  
  51. //在这个案例中,这个测试参数是一个PrimeTableFactory接口的指针  
  52.   
  53. // which we use in fixture's SetUp() to create and store an instance of PrimeTable.  
  54. //我们用这个指针在fixture的SetUp()函数中去创建和存储PrimeTable的一个实例  
  55.   
  56. class PrimeTableTest : public TestWithParam<CreatePrimeTableFunc*> {  
  57. public:  
  58.     virtual ~PrimeTableTest() { delete table_; }  
  59.     virtual void SetUp() { table_ = (*GetParam())(); }  
  60.     virtual void TearDown() {  
  61.         delete table_;  
  62.         table_ = NULL;  
  63.     }  
  64.   
  65. protected:  
  66.     PrimeTable* table_;  
  67. };  
  68.   
  69. TEST_P(PrimeTableTest, ReturnsFalseForNonPrimes) {  
  70.     EXPECT_FALSE(table_->IsPrime(-5));  
  71.     EXPECT_FALSE(table_->IsPrime(0));  
  72.     EXPECT_FALSE(table_->IsPrime(1));  
  73.     EXPECT_FALSE(table_->IsPrime(4));  
  74.     EXPECT_FALSE(table_->IsPrime(6));  
  75.     EXPECT_FALSE(table_->IsPrime(100));  
  76. }  
  77.   
  78. TEST_P(PrimeTableTest, ReturnsTrueForPrimes) {  
  79.     EXPECT_TRUE(table_->IsPrime(2));  
  80.     EXPECT_TRUE(table_->IsPrime(3));  
  81.     EXPECT_TRUE(table_->IsPrime(5));  
  82.     EXPECT_TRUE(table_->IsPrime(7));  
  83.     EXPECT_TRUE(table_->IsPrime(11));  
  84.     EXPECT_TRUE(table_->IsPrime(131));  
  85. }  
  86.   
  87. TEST_P(PrimeTableTest, CanGetNextPrime) {  
  88.     EXPECT_EQ(2, table_->GetNextPrime(0));  
  89.     EXPECT_EQ(3, table_->GetNextPrime(2));  
  90.     EXPECT_EQ(5, table_->GetNextPrime(3));  
  91.     EXPECT_EQ(7, table_->GetNextPrime(5));  
  92.     EXPECT_EQ(11, table_->GetNextPrime(7));  
  93.     EXPECT_EQ(131, table_->GetNextPrime(128));  
  94. }  
  95.   
  96. // In order to run value-parameterized tests, you need to instantiate them,  
  97. // or bind them to a list of values which will be used as test parameters.  
  98. //为了运行这个值参数化测试,你需要实例化他们并且把他们绑定到可能被用作测试参数的一系列值上  
  99. //  
  100. // You can instantiate them in a different translation module, or even  
  101. // instantiate them several times.  
  102. //你可以在一个不同的调用模块实例化他们,甚至可以实例化他们多次  
  103.   
  104. // Here, we instantiate our tests with a list of two PrimeTable object  
  105. // factory functions:  
  106. //在这里,我们利用两个PrimeTable实体工程方法的列表来实例化我们的测试  
  107.   
  108. INSTANTIATE_TEST_CASE_P(  
  109.                         OnTheFlyAndPreCalculated,  
  110.                         PrimeTableTest,  
  111.                         Values(&CreateOnTheFlyPrimeTable, &CreatePreCalculatedPrimeTable<1000>));  
  112.   
  113. #else  
  114.   
  115. // Google Test doesn't support value-parameterized tests on some platforms and compilers, such as MSVC 7.1.  
  116. //gtest 在一些平台或编译器上并不至此值参数化测试,例如MSVC 7.1平台  
  117. //  If we use conditional compilation to  
  118. // compile out all code referring to the gtest_main library, MSVC linker  
  119. // will not link that library at all and consequently complain about  
  120. // missing entry point defined in that library (fatal error LNK1561:  
  121. // entry point must be defined). This dummy test keeps gtest_main linked in.  
  122. TEST(DummyTest, ValueParameterizedTestsAreNotSupportedOnThisPlatform) {}  
  123.   
  124. #endif  // GTEST_HAS_PARAM_TEST  

 

 

 

GTest_Test.cpp测试入口函数

Cpp代码   收藏代码
  1. #include "stdafx.h"  
  2. #include <gtest/gtest.h>  
  3. #include <iostream>  
  4. using namespace std;  
  5.   
  6. int _tmain(int argc, _TCHAR* argv[])  
  7. {  
  8.     std::cout << "Running main() from gtest_main.cc\n";  
  9.     //testing::AddGlobalTestEnvironment(new FooEnvironment);  
  10.     testing::InitGoogleTest(&argc, argv);  
  11.     return RUN_ALL_TESTS();  
  12. }  

 

网址:http://mzhx-com.iteye.com/blog/1673469

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值