我想应用参数化测试并具有以下功能:
class MyTest: public ::testing::TestWithParam<float> {...};
我想设置两个参数化的测试用例,其中一个参数较小的失败,但是较大的成功。
TEST_P(MyTest, smallParamsFail)
{
auto param = GetParam();
EXPECT_EQ(true, param<1);
}
TEST_P(MyTest, largeParamsSucceed)
{
auto param = GetParam();
EXPECT_EQ(true, param>1);
}
我现在想以较小的值开始测试用例smallParamsFail,以较小的值开始另一个。不幸的是,我只能像这样对整个测试进行参数设置:
INSTANTIATE_TEST_CASE_P(
testLargeParams,
MyTest,
::testing::Values(2.0f, 3.14f));
这将同时执行两个测试用例,并且显然在case smallParamsFail上崩溃。我需要的是仅在测试用例largeParamsSucceed上使用参数2.0f,3.14f实例化MyTest。然后使用适当的参数以相同的方式启动另一种情况。
答案 0 :(得分:2)
在yksisarvinen评论中已经提到,在GTest中是不可能的。
我将使用以下解决方法
class MyTestBase: public ::testing::TestWithParam<float> {
protected:
MyTestBase() {
// whatever
}
// whatever
int someParam_;
};
class MyTestForSmall: public MyTestBase {
};
class MyTestForBig: public MyTestBase {
};
TEST_P(MyTestForSmall, smallParamsFail) {
auto param = GetParam();
EXPECT_EQ(true, param<1);
}
TEST_P(MyTestForBig, largeParamsSucceed) {
auto param = GetParam();
EXPECT_EQ(true, param>1);
}
TEST_P(MyTestBase, someGeneralTest) {
auto param = GetParam();
EXPECT_TRUE(true);
}
INSTANTIATE_TEST_CASE_P(
testSmallParams,
MyTestForSmall,
::testing::Values(0.1, 0.2));
INSTANTIATE_TEST_CASE_P(
testLargeParams,
MyTestForBig,
::testing::Values(2.0f, 3.14f));
INSTANTIATE_TEST_CASE_P(
allKindsOfParams,
MyTestBase,
::testing::Values(0.1, 0.2, 2.0f, 3.14f));
在基类中,您可以设置所有必要的环境,并仅将子类用于测试参数的分离。
可能的输出:
[----------] 2 tests from testSmallParams/MyTestForSmall
[ RUN ] testSmallParams/MyTestForSmall.smallParamsFail/0
[ OK ] testSmallParams/MyTestForSmall.smallParamsFail/0 (0 ms)
[ RUN ] testSmallParams/MyTestForSmall.smallParamsFail/1
[ OK ] testSmallParams/MyTestForSmall.smallParamsFail/1 (0 ms)
[----------] 2 tests from testSmallParams/MyTestForSmall (0 ms total)
[----------] 2 tests from testLargeParams/MyTestForBig
[ RUN ] testLargeParams/MyTestForBig.largeParamsSucceed/0
[ OK ] testLargeParams/MyTestForBig.largeParamsSucceed/0 (0 ms)
[ RUN ] testLargeParams/MyTestForBig.largeParamsSucceed/1
[ OK ] testLargeParams/MyTestForBig.largeParamsSucceed/1 (0 ms)
[----------] 2 tests from testLargeParams/MyTestForBig (0 ms total)
[----------] 4 tests from allKindsOfParams/MyTestBase
[ RUN ] allKindsOfParams/MyTestBase.someGeneralTest/0
[ OK ] allKindsOfParams/MyTestBase.someGeneralTest/0 (0 ms)
[ RUN ] allKindsOfParams/MyTestBase.someGeneralTest/1
[ OK ] allKindsOfParams/MyTestBase.someGeneralTest/1 (0 ms)
[ RUN ] allKindsOfParams/MyTestBase.someGeneralTest/2
[ OK ] allKindsOfParams/MyTestBase.someGeneralTest/2 (0 ms)
[ RUN ] allKindsOfParams/MyTestBase.someGeneralTest/3
[ OK ] allKindsOfParams/MyTestBase.someGeneralTest/3 (0 ms)
[----------] 4 tests from allKindsOfParams/MyTestBase (0 ms total)