sev*_*axx 17 c++ unit-testing memory-leaks visual-studio
我正在尝试为我的代码实现单元测试,而且我很难做到这一点.
理想情况下,我想测试一些类,不仅是为了良好的功能,还为了正确的内存分配/释放.我想知道是否可以使用单元测试框架完成此检查.我正在使用Visual Assert btw.如果可能的话,我希望看到一些示例代码!
Chr*_*cke 15
您可以使用调试功能直接进入dev studio来执行泄漏检查 - 只要您的单元测试'使用debug c-runtime运行.
一个简单的例子看起来像这样:
#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 );
}
};
Run Code Online (Sandbox Code Playgroud)
并在单元测试中使用它:
UNIT_TEST(blah)
{
CrtCheckMemory check;
// TODO: add the unit test here
}
Run Code Online (Sandbox Code Playgroud)
一些单元测试框架进行自己的分配 - 例如Google在单元测试失败时分配块,因此任何因任何其他原因而失败的测试块也总是存在误报"泄漏".
您可以使用Google的tcmalloc分配库,它提供了heapchecker.
(请注意,heapchecking可能会为程序的性能增加明显的开销,因此您可能只想在调试版本或单元测试中启用它.)
你问了示例代码,所以在这里.