Garmaine Staff asked 2 years ago

I would like to know if there is anyway I can write a gmock unit test in C++ that does not call the constructor of the existing fixture class.

My question is specific to existing code hence first I will summarize how existing code is structured.

In the C++ file, all the existing unit tests use the fixture. The constructor of that fixture builds configuration needed to execute all those unit tests.

The code in that file looks something like this.

class TestHandlerFixture : public HandlerFixture
{
public:
    TestHandlerFixture()
    {
        // Lot of code here including below call
        HandlerImplemantaion::create_link(Arg1);
    }
    ~TestHandlerFixture()
    {
        // Code to clean up
    }
}


BOOST_FIXTURE_TEST_SUITE(TestHandler, TestHandlerFixture);

BOOST_AUTO_TEST_CASE(test_one)
{

}

BOOST_AUTO_TEST_CASE(test_two)
{

}

// Lot more unit tests

BOOST_AUTO_TEST_SUITE_END();

I modified code that is called by the create_link() function and hence I want to add a new unit test to test the new code. The new code that I added is an error case and is not applicable to the regular flow of the create_link(). In the new test, I want to set error condition first and then assert using EXPECT_CALL(…) when create_link() is called. Any idea how to do that without affecting the existing test cases or significantly modifying the existing unit tests?

Since create_link() is called inside the constructor and hence it executes for every test, I don't think I can set error condition inside the constructor since it will affect all the existing tests. I can delete create_link() call from the constructor and then explicitly call it in every unit test but that than I have to make changes in lot of places. I would like to know if there is any other way I can write unit test without significantly impacting existing tests. Is there way I can write unit test that does not call the constructor of the TestHandlerFixture class?

My idea about new unit test is something like this.

BOOST_AUTO_TEST_CASE(test_create_link_error)
{
    // Code here to set error condition
    EXPECT_CALL(...); // This check for error when create_link() is called.
    create_link(Arg1);
}

The above code does not work since TestHandlerFixture() constructor gets called first and hence it calls create_link(). Thanks.