Google测试:有没有办法组合一个既可以参数化又可以参数化值的测试?

时间:2011-12-14 15:48:27

标签: unit-testing googletest parameterized-unit-test

我知道如何分别开发类型参数化测试和值参数化测试。我想弄清楚的是,是否可以将两者结合起来。换句话说,创建一个通用测试,该测试采用该类型的任何类型和范围的值。

1 个答案:

答案 0 :(得分:19)

没有任何现成的类型参数化测试组合 和价值参数化测试。 googletest开发者已经asked the question and they said No.

然而,有一种常规且简单的方法(如链接讨论中的Zhanyong Wan所建议的那样)你可以自己制作 类型参数化测试用例,用于测试指定范围的某些条件 参数类型的值。这是一个基本的例子 条件只是大于0

#include <vector>
#include "gtest/gtest.h"

template<class T>
struct foo_test : public ::testing::Test {
    static std::vector<T> _range_;
};

TYPED_TEST_CASE_P(foo_test);

TYPED_TEST_P(foo_test, IsGreaterThanZero) {
    for (TypeParam value : foo_test<TypeParam>::_range_) {
        EXPECT_GT(value,0);
    }
}

REGISTER_TYPED_TEST_CASE_P(foo_test,IsGreaterThanZero);

typedef ::testing::Types<char, int, float> MyTypes;
INSTANTIATE_TYPED_TEST_CASE_P(My, foo_test, MyTypes);

template<> std::vector<char> foo_test<char>::_range_{'1','2','3'};
template<> std::vector<int> foo_test<int>::_range_{1,2,3};
template<> std::vector<float> foo_test<float>::_range_{1.1,2.2,0.0};

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

编译并运行时,输出为:

[==========] Running 3 tests from 3 test cases.
[----------] Global test environment set-up.
[----------] 1 test from My/foo_test/0, where TypeParam = char
[ RUN      ] My/foo_test/0.IsGreaterThanZero
[       OK ] My/foo_test/0.IsGreaterThanZero (0 ms)
[----------] 1 test from My/foo_test/0 (0 ms total)

[----------] 1 test from My/foo_test/1, where TypeParam = int
[ RUN      ] My/foo_test/1.IsGreaterThanZero
[       OK ] My/foo_test/1.IsGreaterThanZero (0 ms)
[----------] 1 test from My/foo_test/1 (0 ms total)

[----------] 1 test from My/foo_test/2, where TypeParam = float
[ RUN      ] My/foo_test/2.IsGreaterThanZero
/home/imk/develop/SO/gtest/main.cpp:14: Failure
Expected: (value) > (0), actual: 0 vs 0
[  FAILED  ] My/foo_test/2.IsGreaterThanZero, where TypeParam = float (0 ms)
[----------] 1 test from My/foo_test/2 (1 ms total)

[----------] Global test environment tear-down
[==========] 3 tests from 3 test cases ran. (1 ms total)
[  PASSED  ] 2 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] My/foo_test/2.IsGreaterThanZero, where TypeParam = float

1 FAILED TEST

结果的粒度比理想的要粗:只有3个测试 如图所示,可以报告失败的值,因此粗粒可能很好 可容忍的。