由于我自己无法弄清楚如何将 TemplateRex 的答案与 Puchatek 的原始 sn-p 结合起来,这里有一个完整的可编译示例。我是通过阅读 GTest's own comments 得到的,这很有帮助。
将以下内容放入test.cpp:
#include <gtest/gtest.h>
#include <regex>
#include <vector>
using vector_typelist = testing::Types<char, int*, std::regex>;
template<class> struct vector_suite : testing::Test {};
TYPED_TEST_SUITE(vector_suite, vector_typelist);
TYPED_TEST(vector_suite, bigness)
{
std::vector<TypeParam> v;
EXPECT_TRUE(sizeof(v) >= sizeof(TypeParam));
}
使用适当的-I 和-l 选项进行编译。这可能看起来像:
g++ -std=c++14 -I/usr/local/include test.cpp -L/usr/local/lib -lgtest -lgtest_main
或者(如果你使用pkg-config):
g++ -std=c++14 $(pkg-config --cflags gtest) test.cpp $(pkg-config --libs gtest_main)
运行可执行文件,您应该会看到如下内容:
$ ./a.out
Running main() from /foobar/gtest_main.cc
[==========] Running 3 tests from 3 test suites.
[----------] Global test environment set-up.
[----------] 1 test from vector_suite/0, where TypeParam = char
[ RUN ] vector_suite/0.bigness
[ OK ] vector_suite/0.bigness (0 ms)
[----------] 1 test from vector_suite/0 (0 ms total)
[----------] 1 test from vector_suite/1, where TypeParam = int*
[ RUN ] vector_suite/1.bigness
[ OK ] vector_suite/1.bigness (0 ms)
[----------] 1 test from vector_suite/1 (0 ms total)
[----------] 1 test from vector_suite/2, where TypeParam = std::basic_regex<char, std::__1::regex_traits<char> >
[ RUN ] vector_suite/2.bigness
test.cpp:12: Failure
Value of: sizeof(v) >= sizeof(TypeParam)
Actual: false
Expected: true
[ FAILED ] vector_suite/2.bigness, where TypeParam = std::basic_regex<char, std::__1::regex_traits<char> > (0 ms)
[----------] 1 test from vector_suite/2 (0 ms total)
[----------] Global test environment tear-down
[==========] 3 tests from 3 test suites ran. (0 ms total)
[ PASSED ] 2 tests.
[ FAILED ] 1 test, listed below:
[ FAILED ] vector_suite/2.bigness, where TypeParam = std::basic_regex<char, std::__1::regex_traits<char> >
1 FAILED TEST
(我放入这个失败的测试纯粹是为了演示当类型化测试失败时会发生什么。事实上sizeof(std::vector<std::regex>) 确实小于sizeof(std::regex)。)
请注意,TYPED_TEST 会生成一系列具有相关但名称不同的测试套件。不再有单个vector_suite:
$ ./a.out --gtest_filter=vector_suite.*
Running main() from /foobar/gtest_main.cc
Note: Google Test filter = vector_suite.*
[==========] Running 0 tests from 0 test suites.
[==========] 0 tests from 0 test suites ran. (0 ms total)
[ PASSED ] 0 tests.
取而代之的是vector_suite/0、vector_suite/1和vector_suite/2:
$ ./a.out --gtest_filter=vector_suite/0.*
Running main() from /foobar/gtest_main.cc
Note: Google Test filter = vector_suite/0.*
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from vector_suite/0, where TypeParam = char
[ RUN ] vector_suite/0.bigness
[ OK ] vector_suite/0.bigness (0 ms)
[----------] 1 test from vector_suite/0 (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[ PASSED ] 1 test.