I've created a class in which there's some new operator in the constructor. I've created the guard into the constructor to manage new operator failing, but now I want to test it.
As example, I've a constructor that is like this:
Function::Function()
{
try
{
m_pxArgument = new Argument();
}
catch(std::bad_alloc)
{
throw MemoryException();
}
}
Is it possible to create a test in which I can tell the new operator to fail, to test my catch code?
If Argument
is your class/struct - then define operator new in this class just for UT purposes.
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
};
Just set Argument::failNew() = true;
every time you need to fail its allocation.