【发布时间】:2015-08-18 20:45:32
【问题描述】:
目前,IMO、Google 类型参数化测试很烦人。你必须这样做:
template <typename fixtureType>
class testFixtureOld : public ::testing::Test
{
};
// Tell google test that we want to test this fixture
TYPED_TEST_CASE_P(testFixtureOld);
// Create the tests using this fixture
TYPED_TEST_P(testFixtureOld, OIS1Old)
{
TypeParam n = 0;
EXPECT_EQ(n, 0);
}
TYPED_TEST_P(testFixtureOld, OIS2Old)
{
TypeParam n = 0;
EXPECT_EQ(n, 0);
}
// Register the tests we just made
REGISTER_TYPED_TEST_CASE_P(testFixtureOld, OIS1Old, OIS2Old);
// Run the tests
typedef ::testing::Types<char, int, unsigned int> TypesTestingOld;
INSTANTIATE_TYPED_TEST_CASE_P(RunOldTests, testFixtureOld, TypesTestingOld);
这些东西中的大部分似乎都可以实现自动化。例如:
#define TYPED_TESTS_P(fixture, testName1, test1, testName2, test2) TYPED_TEST_CASE_P(fixture); TYPED_TEST_P(fixture, testName1) test1 TYPED_TEST_P(fixture, testName2) test2 REGISTER_TYPED_TEST_CASE_P(fixture, testName1, testName2);
#define RUN_TYPED_TESTS_P(testSuiteName, fixture, type1, type2, type3) typedef::testing::Types<type1, type2, type3> TypesTesting; INSTANTIATE_TYPED_TEST_CASE_P(testSuiteName, fixture, TypesTesting);
template <typename fixtureType>
class testFixtureNew : public ::testing::Test
{
};
// Make our tests. This tells google test that we want to test this fixture,
// creates the tests using this fixture, and registers them.
TYPED_TESTS_P(testFixtureNew,
OISNew,
{
TypeParam n = 0;
EXPECT_EQ(n, 0);
},
OIS2New,
{
TypeParam n = 0;
EXPECT_EQ(n, 0);
}
)
// Run the tests
RUN_TYPED_TESTS_P(RunNewTests, testFixtureNew, char, int, unsigned int);
(这些宏可以很容易地扩展到一个非常大的尺寸,然后它们就足以满足大多数用途)
这行得通,但是,这种语法相当不正常,所以我想让它看起来更正常,以便更具可读性。这需要一种方法来做这样的事情:
#include <std>
using namespace std;
#define PassIntoThenListOut(inArg, fun1, fun2) something
PassIntoThenListOut(6,
int a(int foo)
{
cout << "5+first = " << (5+foo);
},
int b(int bar)
{
cout << "10+second = " << (10+bar);
}
)
// Should output:
// 5+first = 11
// 10+second = 16
// ArgumentNames: foo bar
我不确定这是否可行。这可能吗?
我会简单地发布最后一段代码,但其他人似乎认为想象一个用例太晦涩难懂,所以我也想提供它。
【问题讨论】:
-
看起来你在谈论Type-Parameterised Tests,而不是更简单的Typed Tests,后者使用起来有点乏味。
-
我认为原始语法并没有那么糟糕,但如果我要为它制作任何语法糖,我会首先尝试深入研究 Google 提供的宏,看看它们生成了什么,什么是真的需要实现。对于宏,您最好检查一下,例如我在 SO 上的某个地方发布了关于如何以可移植的方式通过参数分发宏调用的帖子。也就是说,要有现实的期望:几乎每个人都会做这种事情一两次或三次,这个想法一开始看起来很棒,做起来很有趣/有趣,但后来……一个人不使用它。学习一些! :)
-
哦,另外,有时 C++ 预处理器或 TMP 编程不是生成代码的正确工具。有时,只需要一点脚本和源代码生成即可。 ;-)
-
@IKavanagh,问题是如何做最后一段代码。你们可能是对的,有更好的工具可以解决这个问题,但我仍然想知道是否有可能使用 c++ 预处理器获得最后一段代码所需的行为(不管使用预处理器是否是最好的方法来实现它)。
-
@Fraser 是的,对不起,你是对的。
标签: c++ macros c-preprocessor googletest