Search code examples
c++unit-testinggoogletest

How do I run a test with multiple sets of initial conditions?


I currently have a suite of tests which are are part of a test fixture. I want to run the same set of tests with a different test fixture too.

How do I do this without actually having to copy-paste the tests and 'manually' changing the test fixture name (as shown below)?

class Trivial_Test : public ::testing::Test
{
    void SetUp()
    {
        ASSERT_TRUE(SUCCESS == init_logger());
        initial_condition = 0;
    }

    void TearDown()
    {
        shutdown_logger();
    }

    protected:
    int initial_condition;
};

class Trivial_Test_01 : public ::testing::Test
{
    void SetUp()
    {
        ASSERT_TRUE(SUCCESS == init_logger());
        initial_condition = 1;
    }

    void TearDown()
    {
        shutdown_logger();
    }

    protected:
    int initial_condition;
};

TEST_F(Trivial_Test, valid_input_1)
{
    EXPECT_TRUE(random_num()+initial_condition < 255);
}

TEST_F(Trivial_Test_01, valid_input_1)
{
    EXPECT_TRUE(random_num()+initial_condition < 255);
}

Is there a less verbose way of associating valid_input_1 with both Trivial_Test and Trivial_Test_01?

P.S. - The test case shown above is a trivial test which nominally represents my actual situation but nowhere close to the complexity of the testcases or testfixtures I am actually dealing with.


Solution

  • Did you consider value parameterized tests?

    Maybe for your actual test cases it adds too much complexity, but your example would look like:

    class Trivial_Test : public ::testing::TestWithParam<int>
    {
        void SetUp()
        {
             ASSERT_TRUE(SUCCESS == init_logger());
        }
        void TearDown()
        {
            shutdown_logger();
        }
    };
    
    TEST_F(Trivial_Test, valid_input)
    {
        int initial_condition = GetParam();
        EXPECT_TRUE(random_num()+initial_condition < 255);
    }
    
    INSTANTIATE_TEST_CASE_P(ValidInput,
                            Trivial_Test,
                            ::testing::Values(0, 1));