Home > Software design >  How to dynamically create a lot of data for INSTANTIATE_TEST_CASE_P parameterized unit tests
How to dynamically create a lot of data for INSTANTIATE_TEST_CASE_P parameterized unit tests

Time:07-31

I need help with INSTANTIATE_TEST_CASE_P(prefix, test, testing::ValuesIn(container)).

Running VS 2022 and latest google test ("Microsoft.googletest.v140.windesktop.msvcstl.static.rt-dyn" version="1.8.1.5")

The problem is, INSTANTIATE_TEST_CASE_P appears to only use the data in the container at compile time. I've tried everything to add more at runtime, before any tests run, without success (e.g., using SetUpTestSuite and SetUpEnvironment as mentioned enter image description here

CodePudding user response:

The generator expressions (including parameters to the generator) are evaluated in InitGoogleTest(). Therefore, it is necessary to read the data and put it to g_data_in_file before InitGoogleTest() is called in main function. And Environment::SetUp() is called only from RUN_ALL_TESTS(). So, it's too late to read the data for the parameterized test in Environment::SetUp().

But you can change a little bit the LoadTestData() function:

...
std::vector<TestData> LoadTestData()
{
    std::vector<TestData> test_data;
    //...just reads a text file line by line adding N number of TestData...
    return test_data;
}
...
INSTANTIATE_TEST_CASE_P(TestsFromFile, ParamTest, testing::ValuesIn(LoadTestData()));

and it will work as expected.

  • Related