Why does a test fixture have a SetUp method in Google Test? Isn't the Constructor effectively the same thing? Likewise for the TearDown method. Calls to both SetUp and the Constructor, as well as TearDown and the Destructor, are consistent with the TestEventListeners: OnTestStart and OnTestEnd.
There is an answer to that in the FAQ:
Should I use the constructor/destructor of the test fixture or the set-up/tear-down function?
The first thing to remember is that googletest does not reuse the same test fixture object across multiple tests. For each
TEST_F
, googletest will create a fresh test fixture object, immediately callSetUp()
, run the test body, callTearDown()
, and then delete the test fixture object.When you need to write per-test set-up and tear-down logic, you have the choice between using the test fixture constructor/destructor or
SetUp()/TearDown()
. The former is usually preferred, as it has the following benefits:
- By initializing a member variable in the constructor, we have the option to make it
const
, which helps prevent accidental changes to its value and makes the tests more obviously correct.- In case we need to subclass the test fixture class, the subclass' constructor is guaranteed to call the base class' constructor first, and the subclass' destructor is guaranteed to call the base class' destructor afterward. With
SetUp()/TearDown()
, a subclass may make the mistake of forgetting to call the base class'SetUp()/TearDown()
or call them at the wrong time.You may still want to use
SetUp()/TearDown()
in the following rare cases:
- In the body of a constructor (or destructor), it's not possible to use the
ASSERT_xx
macros. Therefore, if the set-up operation could cause a fatal test failure that should prevent the test from running, it's necessary to use aCHECK
macro or to useSetUp()
instead of a constructor.- If the tear-down operation could throw an exception, you must use
TearDown()
as opposed to the destructor, as throwing in a destructor leads to undefined behavior and usually will kill your program right away. Note that many standard libraries (like STL) may throw when exceptions are enabled in the compiler. Therefore you should preferTearDown()
if you want to write portable tests that work with or without exceptions.- The googletest team is considering making the assertion macros throw on platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux client-side), which will eliminate the need for the user to propagate failures from a subroutine to its caller. Therefore, you shouldn't use googletest assertions in a destructor if your code could run on such a platform.
- In a constructor or destructor, you cannot make a virtual function call on this object. (You can call a method declared as virtual, but it will be statically bound.) Therefore, if you need to call a method that will be overridden in a derived class, you have to use
SetUp()/TearDown()
.