c++ - 带有 GTest TYPED_TEST 的 C++ 多个参数
问题描述
我有一些闲置的测试:
TEST_F(FactoryShould, createAFromAModule)
{
const auto stateMachine = createStateMachine(EModule_A);
const auto* typedStateMachine =
dynamic_cast<const BackEnd<transitiontable::A, Guard>*>(stateMachine.get());
ASSERT_TRUE(typedStateMachine);
}
TEST_F(FactoryShould, createBFromBModule)
{
const auto stateMachine = createStateMachine(EModule_B);
const auto* typedStateMachine =
dynamic_cast<const BackEnd<transitiontable::B, Guard>*>(stateMachine.get());
ASSERT_TRUE(typedStateMachine);
}
有没有办法把它们变成类型测试?我所看到的只是一个更改参数的解决方案,我有 2 个更改参数,EModule 可以用于多个转换表,所以像 map 这样的东西看起来不错,但它是可行的吗?
解决方案
有了std::pair
您,您可以从任何其他两种中制作一种。(并且std::tuple
您可以从任何其他N中制作一种类型)。
您可以编写 googletest TYPED_TEST
s,其中TypeParam
假设 , 列表中的值std::pair<X,Y>
用于成对的参数类型X
和Y
, 以便此类 a 的每个实例化TYPED_TEST
都X
定义为TypeParam::first_type
和Y
定义为TypeParam::second_type
。例如:
gtester.cpp
#include <gtest/gtest.h>
#include <utility>
#include <cctype>
struct A1 {
char ch = 'A';
};
struct A2 {
char ch = 'a';
};
struct B1 {
char ch = 'B';
};
struct B2 {
char ch = 'b';
};
template <typename T>
class pair_test : public ::testing::Test {};
using test_types = ::testing::Types<std::pair<A1,A2>, std::pair<B1,B2>>;
TYPED_TEST_CASE(pair_test, test_types);
TYPED_TEST(pair_test, compare_no_case)
{
typename TypeParam::first_type param1;
typename TypeParam::second_type param2;
ASSERT_TRUE(param1.ch == std::toupper(param2.ch));
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
编译、链接、运行:
$ g++ -Wall -o gtester gtester.cpp -lgtest -pthread && ./gtester
[==========] Running 2 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 1 test from pair_test/0, where TypeParam = std::pair<A1, A2>
[ RUN ] pair_test/0.compare_no_case
[ OK ] pair_test/0.compare_no_case (0 ms)
[----------] 1 test from pair_test/0 (0 ms total)
[----------] 1 test from pair_test/1, where TypeParam = std::pair<B1, B2>
[ RUN ] pair_test/1.compare_no_case
[ OK ] pair_test/1.compare_no_case (0 ms)
[----------] 1 test from pair_test/1 (0 ms total)
[----------] Global test environment tear-down
[==========] 2 tests from 2 test cases ran. (0 ms total)
[ PASSED ] 2 tests.
推荐阅读
- vert.x - `org.bson.codecs.configuration.CodecConfigurationException` 从 vertx 写入 MongoDB
- python - 如何使用美丽的汤保存页面中的所有图像?
- php - 计算数组中特定数字的值并返回出现次数
- java - switch语句上的“需要常量表达式”?
- java - 在将数据从 firebase 获取到 string[] 数组时需要帮助。尝试了所有可用的方法,但坚持只获得最后一个值
- c# - 在 C# 中从 CSV 读取不同的值到 Datagridview
- javascript - 当我尝试在模拟器上运行时,React Native 失败
- php - SOAP 调用后获取 XML 字段
- c++ - 如何封装函数绑定?
- python-3.x - 如何识别 prargraph 中存在 2 个不同的字符串