Search code examples
c++unit-testinggoogletestfixtures

writing googletests working on predefined object


I want to write unit test witch work on an object. The difference to normal fixtures is, that i don't want the fixture to be run before every test. The SetUp() of the fixture should be run only once, then a couple of tests should be performed. After these tests the TearDown() of the fixture should be performed. I am using googletest in c++. Is there a possibility to achieve this behaviour?


Example to clearify:

#include "gtest/gtest.h"
class socketClientFixture : public testing::Test
{
public:
    CSocketClient *mClient;
    void SetUp()
    {
        mClient = new CSocketClient();
        mClient->connect();
    }
    void TearDown()
    {
        mClient->disconnect();
        delete mClient;
}
TEST_F(socketClientFixture, TestCommandA)
{
    EXPECT_TRUE(mClient->commandA());
}
TEST_F(socketClientFixture, TestCommandB)
{
    EXPECT_TRUE(mClient->commandA());
}
int  main(int ac, char* av[])
{
    ::testing::InitGoogleTest(&ac, av);
    int res = RUN_ALL_TESTS();
    return res;
}

In the example above i don't want the TearDown() to be called after TestCommandA and SetUp() before TestCommandB. The behaviour i want to achieve is:

  1. SetUp()
  2. TestCommandA
  3. TestCommandB
  4. TearDown()

This is due to the fact that the server needs some time after disconnecting to perform some operations.

Any help appreciated.


Solution

  • There is no built in way to do what you ask for, specifically because you are asking for the tests to be ordered.

    You may pull more ideas from this section in the advanced google-test documentation


    If you are willing to sacrifice the test order, you could follow the exact example given in the link above and define static void SetUpTestCase() and static void TearDownTestCase(). Any tests written for that class will participate in the same fixture.

    Do note that if you can avoid this altogether and instantiate the connection as a Mock (see google-mock) it would be a much better alternative. This will decouple your test from the server you want to connect to so you can test your code instead of testing the server. This will also make your tests run much faster.