解读sample5
说明
被测试代码文件 | sample1.h、sample1.cc和sample3-inl.h |
测试代码文件 | sample5_unittest.cc |
官网上如是描述sample5:
Sample #5 is teaches how to reuse a test fixture in multiple test cases by deriving sub-fixtures from it.
sample5演示了如何通过继承的方式来复用fixture class的代码。
由于sample5_unittest.cc里面的class QueueTest,与之前sample中的代码存在命名冲突,所以我另外创建了一个叫做sample5的工程来跑sample5的代码。创建工程的步骤可参考我写的另外一篇文章《用Visual Studio创建集成了gtest的命令行工程》(链接:http://www.cnblogs.com/duxiuxing/p/4272343.html)。
理解被测试代码
sample5的被测试代码来自于前面的sample1和sample3,可以参考之前的文章:
- 《解读sample1》,链接:http://www.cnblogs.com/duxiuxing/p/4273228.html
- 《解读sample3》,链接:http://www.cnblogs.com/duxiuxing/p/4275646.html
理解测试代码
测试代码包含了以下两组test case:
第1组test case的代码是这么组织的:
test fixture/fixture class | IntegerFunctionTest : public QuickTest |
- test name 1 | Factorial:测试Factorial()函数 |
- test name 2 | IsPrime:测试IsPrime()函数 |
第2组test case的代码是这么组织的:
被测试的类 | class Queue |
test fixture/fixture class | QueueTest : public QuickTest |
- test name 1 | DefaultConstructor:测试默认构造函数 |
- test name 2 | Dequeue:测试Dequeue()函数 |
两组test case里面的fixture class都继承于同一个基类“class QuickTest”,这些类的继承关系如下图所示:
关于fixture class继承的建议
sample5的注释里面提出了一个非常不错的建议,可以把各种性能指标(比如执行时长,资源泄露)的检查代码放到基类去完成:
// This sample teaches how to reuse a test fixture in multiple test // cases by deriving sub-fixtures from it. // // When you define a test fixture, you specify the name of the test // case that will use this fixture. Therefore, a test fixture can // be used by only one test case. // // Sometimes, more than one test cases may want to use the same or // slightly different test fixtures. For example, you may want to // make sure that all tests for a GUI library don't leak important // system resources like fonts and brushes. In Google Test, you do // this by putting the shared logic in a super (as in "super class") // test fixture, and then have each test case use a fixture derived // from this super fixture.