如何释放googletest ASSERT_THROW语句中一个函数所使用的资源?

问题描述 投票:0回答:1

在googletest中,你可以使用 ASSERT_THROW 来测试某个函数是否抛出错误。例如

ASSERT_THROW(PhysicalPropertyResource p("other/identifier72652"), InappropriateResourceException);

如何明确地调用另一个方法来释放一些由 PhysicalPropertyResource? 通常是这样使用的。

PhysicalPropertyResource p("other/identifier72652");
p.free();

还是说我不应该担心内存泄漏,因为它只是在测试中,所以是良性的。(这只是我的强迫症,想让valgrind完全满意)。

我试过这个。

    ASSERT_THROW(
            PhysicalPropertyResource p("other/identifier72652");
            p.free();
            , InappropriateResourceException);

}

它不会释放内存。

c++ exception memory-leaks valgrind googletest
1个回答
0
投票

执行多条指令的正确语法是将它们包在一个块中。

ASSERT_THROW({PhysicalPropertyResource p("other/identifier72652");
              p.free();}, 
            InappropriateResourceException);

但是,这并没有什么用,因为不是最后一行抛出的,因为... ... p.free() 将不会被调用。你可以创建你自己的 "断言"

void shouldThrow() {
    std::unique_ptr<PhysicalPropertyResource> p;
    try {
        p = std::make_unique<PhysicalPropertyResource>("other/identifier72652");
    } catch (const InappropriateResourceException&) {
        if (p) //note that this is not possible if it is really constructor that throws
            p->free(); 
        return; //test succeeded
    } catch (...) {
        if (p)
            p->free();
        FAIL();
    }

    if (p)
        p->free;
    FAIL();
}

注意:如果你正在编写使用C库的C++代码,那么你最好的解决方案是创建一个由你自己编写的 RAII 包装器,它将负责处理资源。如果你创建了一个封装类,它可以在destructor中释放资源,你永远不会泄露资源。你甚至可以只为单元测试写这样的包装器,只是为了避免这种丑陋的断言式代码。

© www.soinside.com 2019 - 2024. All rights reserved.