Clean up after exception Google c++ test framework

3.3k Views Asked by At

I am using C++ unit tests using the google unit test framework (fixtures), clean up after the tests is very important for me. But in case of an exception the executable crashes and the clean up never happens. Is there a way to force the clean up even in case of exceptions?

1

There are 1 best solutions below

1
On

Test Fixtures have special methods for constructing and destructing.
They are called SetUp() and TearDown().

Place the appropriate clean-up code inside your TearDown() method.

class FooTest : public ::testing::Test
{
     TestObject *object;
     virtual void SetUp()
     {      
         TestObject = new TestObject();
     }

     virtual void TearDown()
     {
        //clean up occurs when test completes or an exception is thrown
        delete object;
     }
};

It's advised that use smart pointers, and follow RAII practices, but I realize that is not always possible depending on what it is you're testing (legacy C APIs for example).

Apart from that, you can always just catch the exception, and handle the cleanup on catch.