Search code examples
c++googletest

What is the use of a test fixture in google test?


Google recommends to use the text fixture constructor/destructor when possible instead of SetUp()/TearDown() (https://google.github.io/googletest/faq.html#CtorVsSetUp). Assuming I do it this way, what is the use of even using a test fixture? How are the following different, and what is the advantage of the first?

TEST_F(MyFixture, MyTest) {
  ... run test, using member functions of MyFixture for common code ...
}

TEST(MySuite, MyTest) {
  MyFixture fixture; // will call ctor
  ... run test, using public functions of MyFixture for common code ...
} // will call dtor

Solution

  • The advantages are visible when there are more than one TEST/TEST_F. Compare:

    TEST(MyTest, shallX)
    { 
       MyTest test;
       test.setUpX();
       test.objectUnderTest.doX();
    }
    
    TEST(MyTest, shallY)
    {
       OtherTest test;
       test.setUpY();
       test.objectUnderTest.doY();
    }
    

    with

    TEST_F(MyTest, shallX)
    { 
       setUpX();
       objectUnderTest.doX();
    }
    
    TEST_F(MyTest, shallY)
    {
       setUpY();
       objectUnderTest.doY();
    }
    

    What we can see, are:

    1. DRY (don't repeat yourselves) principle is followed. You do not have to repeat creating of some test-helper object. In TEST_F - the macro creates this instance.
    2. The code is safer with TEST_F. See MyTest..shallDoY -- have you spot that wrong test-helper object is used, not the one that testname is promising.

    So it is better to use TEST_F if your tests require some test-helper class. If not - then use TEST.