简体   繁体   English

Google C ++测试框架例外后清理

[英]Clean up after exception Google c++ test framework

I am using C++ unit tests using the google unit test framework (fixtures), clean up after the tests is very important for me. 我使用的是Google单元测试框架(夹具)的C ++单元测试,测试后清理对我来说非常重要。 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? 有没有一种方法可以强制清理,即使有例外情况也可以?

Test Fixtures have special methods for constructing and destructing. 测试治具具有特殊的构造和破坏方法。
They are called SetUp() and TearDown() . 它们分别称为SetUp()TearDown()

Place the appropriate clean-up code inside your TearDown() method. 将适当的清理代码放入TearDown()方法中。

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). 建议使用智能指针 ,并遵循RAII惯例,但我意识到,这并非总是可能的,具体取决于您要测试的内容(例如旧版C API)。

Apart from that, you can always just catch the exception, and handle the cleanup on catch. 除此之外,您始终可以随时捕获异常,并在捕获时进行清理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM