GoogleTest 使用指南 | 测试模板函数

GoogleTest 使用指南 | 测试模板函数 GoogleTest 使用指南 测试模板函数GoogleTest 使用指南 测试模板函数GoogleTest 使用指南 测试模板函数模板类和函数由于其泛型特性需要在不同类型下进行测试以确保其通用性和正确性。下面是一个示例。min.h// min.h#ifndefMIN_H#defineMIN_H// 模板函数的声明和定义都放在头文件中templatetypenameTTmin(T a,T b){return(ab)?a:b;}#endif// MIN_Htest_min.cpp#includegtest/gtest.h#includemin.h// 使用类型化测试templatetypenameTclassMinFunctionTest:public::testing::Test{};typedef::testing::Typesint,double,charTestTypes;TYPED_TEST_SUITE(MinFunctionTest,TestTypes);TYPED_TEST(MinFunctionTest,ReturnSmaller){TypeParam astatic_castTypeParam(5);TypeParam bstatic_castTypeParam(3);EXPECT_EQ(min(a,b),b);EXPECT_EQ(min(b,a),b);}测试的执行结果/Users/xiye/CppProjects/unit-test-example/out/build/Clang 17.0.0 arm64-apple-darwin24.6.0/test_min➜ Clang17.0.0 arm64-apple-darwin24.6.0/Users/xiye/CppProjects/unit-test-example/out/build/Clang 17.0.0 arm64-apple-darwin24.6.0/test_minRunning main()from /Users/xiye/CppProjects/unit-test-example/out/build/Clang17.0.0 arm64-apple-darwin24.6.0/_deps/googletest-src/googletest/src/gtest_main.cc[]Running3tests from3testsuites.[----------]Globaltestenvironment set-up.[----------]1testfrom MinFunctionTest/0, where TypeParamint[RUN]MinFunctionTest/0.ReturnSmaller[OK]MinFunctionTest/0.ReturnSmaller(0ms)[----------]1testfrom MinFunctionTest/0(0ms total)[----------]1testfrom MinFunctionTest/1, where TypeParamdouble[RUN]MinFunctionTest/1.ReturnSmaller[OK]MinFunctionTest/1.ReturnSmaller(0ms)[----------]1testfrom MinFunctionTest/1(0ms total)[----------]1testfrom MinFunctionTest/2, where TypeParamchar[RUN]MinFunctionTest/2.ReturnSmaller[OK]MinFunctionTest/2.ReturnSmaller(0ms)[----------]1testfrom MinFunctionTest/2(0ms total)[----------]Globaltestenvironment tear-down[]3tests from3testsuites ran.(0ms total)[PASSED]3tests.