如何在gtest中参数化测试组?

问题描述 投票:0回答:1

我写了以下示例测试:

// g++ t.cpp -I googletest/include -pthread libgtest{,_main}.a
#include <gtest/gtest.h>

class C : public ::testing::TestWithParam<int>
{
public:
    void SetUp(){
        int n=GetParam();
        std::cout<<"SetUp "<<n<<std::endl;
    }
    static void SetUpTestCase(){
#if 0
        // Condition parameter_ != nullptr failed. GetParam() can only be called inside a value-parameterized test -- did you intend to write TEST_P instead of TEST_F?
        int n=GetParam();
        std::cout<<"SetUpTestCase "<<n<<std::endl;
#endif
        std::cout<<"SetUpTestCase"<<std::endl;
    }
};

TEST_P(C,T1){
    int n=GetParam();
    std::cout<<"T1 "<<n<<std::endl;
}
TEST_P(C,T2){
    int n=GetParam();
    std::cout<<"T2 "<<n<<std::endl;
}

INSTANTIATE_TEST_SUITE_P(S, C, ::testing::Values(1,2));

此测试打印:

Running main() from gtest_main.cc
[==========] Running 4 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 4 tests from S/C
SetUpTestCase
[ RUN      ] S/C.T1/0
SetUp 1
T1 1
[       OK ] S/C.T1/0 (0 ms)
[ RUN      ] S/C.T1/1
SetUp 2
T1 2
[       OK ] S/C.T1/1 (0 ms)
[ RUN      ] S/C.T2/0
SetUp 1
T2 1
[       OK ] S/C.T2/0 (0 ms)
[ RUN      ] S/C.T2/1
SetUp 2
T2 2
[       OK ] S/C.T2/1 (0 ms)
[----------] 4 tests from S/C (0 ms total)

[----------] Global test environment tear-down
[==========] 4 tests from 1 test suite ran. (0 ms total)
[  PASSED  ] 4 tests.

我只想看一次“设置1”。可能吗?我试图在SetUpTestCase()中调用GetParam(),但是它导致了错误Condition parameter_ != nullptr failed. GetParam() can only be called inside a value-parameterized test -- did you intend to write TEST_P instead of TEST_F?。实际上,对于每个测试参数,我的实际设置过程最多可能需要60秒(并且过程结果可以在测试之间共享(此处为T1和T2)),所以我想将过程放入SetUpTestCase()。

c++ googletest
1个回答
0
投票

解决方法可以将资源记录到地图中。

// g++ t.cpp -I googletest/include -pthread libgtest{,_main}.a
#include <gtest/gtest.h>

class C : public ::testing::TestWithParam<int>
{
public:
    void SetUp(){
        int n=GetParam();
        if(sharedResource.find(n)==sharedResource.end()){
            std::cout<<"SetUp "<<n<<std::endl;
            std::shared_ptr<char> p(new char[10000000]);
            sharedResource[n] = p;
        }
    }
    static void TearDownTestCase(){
        std::map<int,std::shared_ptr<char>>::iterator it=sharedResource.begin();
        for(;it!=sharedResource.end();){
            std::cout<<"TearDown "<<it->first<<std::endl;
            it = sharedResource.erase(it);
        }
    }
    static std::map<int,std::shared_ptr<char>>sharedResource;
};
std::map<int,std::shared_ptr<char>> C::sharedResource;

TEST_P(C,T1){
    int n=GetParam();
    std::cout<<"T1 "<<n<<std::endl;
    std::shared_ptr<char> p = sharedResource[n];
}
TEST_P(C,T2){
    int n=GetParam();
    std::cout<<"T2 "<<n<<std::endl;
    std::shared_ptr<char> p = sharedResource[n];
}

INSTANTIATE_TEST_SUITE_P(S, C, ::testing::Values(1,2));
© www.soinside.com 2019 - 2024. All rights reserved.