Skip to content

Latest commit

 

History

History
75 lines (68 loc) · 6.4 KB

2010-03-19-gtest_demo.md

File metadata and controls

75 lines (68 loc) · 6.4 KB
categories date title url
技术文章
2010-03-19
gtest参数化测试代码示例
/2010/03/19/gtest_demo/

玩转 Google开源C++单元测试框架Google Test系列(gtest)之四 - 参数化中已经介绍过了如何使用gtest进行参数化测试。在twitter上应 @xlinker 的要求,我在这里提供一个参数化的完整例子。这个例子也是我当初了解gtest时写的,同时这个例子也在《玩转》系列中出现过。最后,我再附上整个demo工程,里面有一些其他的示例,刚开始上手的同学可以直接拿我的demo工程去试,有任何疑问都欢迎提出。以下是使用TEST_P宏进行参数化测试的示例:

#include "stdafx.h" #include "foo.h" #include <gtest/gtest.h>
class IsPrimeParamTest : public::testing::TestWithParam<int> {
};
// 不使用参数化测试,就需要像这样写五次 TEST(IsPrimeTest, HandleTrueReturn) {     EXPECT_TRUE(IsPrime(3));     EXPECT_TRUE(IsPrime(5));     EXPECT_TRUE(IsPrime(11));     EXPECT_TRUE(IsPrime(23));     EXPECT_TRUE(IsPrime(17)); }
// 使用参数化测试,只需要: TEST_P(IsPrimeParamTest, HandleTrueReturn) {     int n =  GetParam();     EXPECT_TRUE(IsPrime(n)); }
// 定义参数 INSTANTIATE_TEST_CASE_P(TrueReturn, IsPrimeParamTest, testing::Values(
35112317));
// ----------------------- // 更复杂一点的参数结构 struct NumberPair {     NumberPair(int _a, int _b)     {         a = _a;         b = _b;     }     int a;     int b; };
class FooParamTest : public ::testing::TestWithParam<NumberPair> {
};
TEST_P(FooParamTest, HandleThreeReturn) {     FooCalc foo;     NumberPair pair 
= GetParam();     EXPECT_EQ(3, foo.Calc(pair.a, pair.b)); }
INSTANTIATE_TEST_CASE_P(ThreeReturn, FooParamTest, testing::Values(NumberPair(
1215), NumberPair(1821)));

完整示例工程:

/Files/coderzh/Code/gtest_demo.rar 

[温馨提示]:该文章由原博客园导入而来,如排版效果不佳,请移步:http://www.cnblogs.com/coderzh/archive/2010/03/19/gtest_demo.html