我正在尝试为我的代码实现单元测试,但我很难做到。
理想情况下,我想测试一些类,不仅是为了获得良好的功能,还要为了正确的内存分配/释放。我想知道这个检查是否可以使用单元测试框架来完成。我正在使用 Visual Assert顺便提一句。如果可能的话,我希望看到一些示例代码!
最佳答案
您可以直接在 dev studio 中使用调试功能来执行泄漏检查 - 只要您的单元测试使用调试 c 运行时运行。
一个简单的例子如下所示:
#include <crtdbg.h>
struct CrtCheckMemory
{
_CrtMemState state1;
_CrtMemState state2;
_CrtMemState state3;
CrtCheckMemory()
{
_CrtMemCheckpoint(&state1);
}
~CrtCheckMemory()
{
_CrtMemCheckpoint(&state2);
// using google test you can just do this.
EXPECT_EQ(0,_CrtMemDifference( &state3, &state1, &state2));
// else just do this to dump the leaked blocks to stdout.
if( _CrtMemDifference( &state3, &state1, &state2) )
_CrtMemDumpStatistics( &state3 );
}
};
并在单元测试中使用它:
UNIT_TEST(blah)
{
CrtCheckMemory check;
// TODO: add the unit test here
}
一些单元测试框架会自行分配 - 例如,Google 会在单元测试失败时分配 block ,因此任何因任何其他原因失败的测试 block 也总是会出现误报“泄漏”。
关于C++ - 是否可以在单元测试中实现内存泄漏测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2980917/