Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 956
work.bin Avatar asked Sep 27 '22 04:09

work.bin


2 Answers

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));
like image 158
Antonio Pérez Avatar answered Sep 30 '22 06:09

Antonio Pérez


You can do this using a method in a fixture class. Here is how you would do this for you example:

class Trivial_Test : public ::testing::Test
{
    void SetUp()
    {
         ASSERT_TRUE(SUCCESS == init_logger());
    }
    void TearDown()
    {
        shutdown_logger();
    }
    setup_initial_condition(int value)
    {
        initial_condition = value;
    }

    protected:
    int initial_condition;
};

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

TEST_F(Trivial_Test, valid_input_2)
{
    setup_initial_condition(1);
    EXPECT_TRUE(random_num()+initial_condition < 255);
}
like image 31
Marko Popovic Avatar answered Sep 30 '22 06:09

Marko Popovic