c++ - 测试新运算符(operator)失败

标签 c++ unit-testing boost boost-test

我创建了一个类,其中的构造函数中有一些 new 运算符。我已将守卫创建到构造函数中以管理新运算符失败,但现在我想测试它。

例如,我有一个这样的构造函数:

Function::Function()
{
  try
  {
    m_pxArgument = new Argument();
  }
  catch(std::bad_alloc)
  {
    throw MemoryException();
  }
}

是否可以创建一个测试,我可以在其中告诉新运算符(operator)失败,以测试我的 catch 代码?

最佳答案

如果 Argument 是您的类/结构 - 则仅出于 UT 目的在此类中定义运算符 new。

class Argument {
//...
#ifdef UNIT_TEST
   static bool& failNew() { static bool failNew = false; return failNew; }
   void* operator new(size_t size)
   {
       if (!failNew())
         return ::operator new (size);
       failNew() = false;       
       throw std::bad_alloc("Argument");
   }
#endif
};

每次需要使其分配失败时,只需设置 Argument::failNew() = true;

关于c++ - 测试新运算符(operator)失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12445729/

相关文章:

c++ - arm-linux-androideabi STL编译报错

c++ - 错误 : cannot call member function 'void Fortest::run()' without object|

angularjs - 使用 jasmine 对 karma 运行超过 10 次测试导致 : "ERROR: Some of your tests did a full page reload!"

c++ - bjam,如何找到 boost 构建

c++ - 在不知道是哪个类的情况下调用C++成员函数指针

c++ - 如何继承一些候选的多态函数?

c - 为什么链接存档时会出现 'multiple definition' 错误?

php - 无法调用具有多个方法参数的命令

c++ - 为什么在 boost python vector 索引套件中需要比较运算符?

c++ - 在 boost::posix_time::ptime 和 mongo::Date_t 之间转换