我创建了一个类,其中的构造函数中有一些 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/