C ++-是否可以在单元测试中实现内存泄漏测试? [英] C++ - Is it possible to implement memory leak testing in a unit test?

查看:74
本文介绍了C ++-是否可以在单元测试中实现内存泄漏测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的代码实施单元测试,但我很难做到.

I'm trying to implement unit testing for my code and I'm having a hard time doing it.

理想情况下,我不仅要测试某些类以获得良好的功能,还要测试适当的内存分配/重新分配.我想知道是否可以使用单元测试框架来完成此检查.我正在使用视觉声明顺便说一句.如果可能的话,我希望看到一些示例代码!

Ideally I would like to test some classes not only for good functionality but also for proper memory allocation/deallocation. I wonder if this check can be done using a unit testing framework. I am using Visual Assert btw. I would love to see some sample code , if possible !

推荐答案

只要您的单元测试使用调试c-runtime运行,您就可以直接使用dev Studio中的调试功能来执行泄漏检查.

You can use the debug functionality right into dev studio to perform leak checking - as long as your unit tests' run using the debug c-runtime.

一个简单的示例如下所示:

A simple example would look something like this:

#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 );
  }
};

并在单元测试中使用它:

And to use it in a unit test:

UNIT_TEST(blah)
{
  CrtCheckMemory check;

  // TODO: add the unit test here

}

某些单元测试框架会自行分配-例如,Google会在单元测试失败时分配块,因此任何因其他原因而失败的测试块也总是会出现假阳性的泄漏".

Some unit test frameworks make their own allocations - Google's for example allocates blocks when a unit test fails, so any test block that has a fail for any other reason always also has a false positive "leak".

这篇关于C ++-是否可以在单元测试中实现内存泄漏测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆