Google C++ Testing Framework之参数化

回到第一节所编写的测试案例上,我们看到虽然只有短短的六个检查点,但我已经可以使用复制粘帖5次之多。

而在大型项目的单元测试上,一个案例往往具有更多 的测试点,而如此多的测试点都编写一行代码的话,一来代码量过大浪费时间,二来也使得编译器不够美观。

不过呢,GoogleTest AdvanceGuide 的参数化功能很好的帮我们解决了这个问题。

开始。

  1. 首先,我们先定义一个类,继承自 ::testing::TestWithParam , 这里的 T 就是我们需要参数化的参数类型了。而 TestWithParam 则是继承自 ::testing:Test 。所以第一节所定义的类为:
class FooTest : public ::testing::TestWithParam<const char*> 
{   // You can implement all the usual fixture class members here.
    // To access the test parameter, call GetParam() from class
    // TestWithParam<T>. 
};
  1. 使用宏 TEST_P 定义你所想要进行的测试。
1 TEST_P(IsPrimeParamTest, TrueReturn)2 {3     //在一个测试案例里面,使用GetParam()传递参数4      int n =  GetParam();5     EXPECT_TRUE(IsPrime(n));6 }
  1. 使用INSTANTIATE_TEST_CASE_P告诉gtest你所要测的参数范围。
1 INSTANTIATE_TEST_CASE_P(TrueCondition, 2                         IsPrimeParamTest, 3                                      ::testing::Values(2, 3, 5, 7, 11, 17));

至此,大功告成。运行之,得结果:

Google C++ Testing Framework之参数化

另:INSTANTIATE_TEST_CASE_P 的第三个函数为参数生成器,有如下一系列函数:

Range(begin, end[, step]) Yields values{begin, begin+step, begin+step+step, ...}. The values do not includeend.stepdefaults to 1.
Values(v1, v2, ..., vN) Yields values{v1, v2, ..., vN}.
ValuesIn(container)andValuesIn(begin, end) Yields values from a C-style array, an STL-style container, or an iterator range[begin, end).
Bool() Yields sequence{false, true}.
Combine(g1, g2, ..., gN) Yields all combinations (the Cartesian product for the math savvy) of the values generated by theNgenerators. This is only available if your system provides theheader. If you are sure your system does, and Google Test disagrees, you can override it by definingGTEST_HAS_TR1_TUPLE=1.

总结。

gtest的参数化功能真正做到了为程序员和编译器减负!
原文链接: https://www.cnblogs.com/way_testlife/archive/2010/10/18/1855092.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/16223

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月7日 下午4:29
下一篇 2023年2月7日 下午4:30

相关推荐