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?
Asked
Active
Viewed 2,878 times
0
-
1Catch the exceptions? – Fantastic Mr Fox Jun 29 '16 at 23:25
1 Answers
0
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.

Trevor Hickey
- 36,288
- 32
- 162
- 271