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.

其他提示

To do such a test you would need to overload operator new for your class Argument and then provide a definition that throws in your test case. However, since that can not be easily exchanged at run time you might need a separate test program.

If you would be my C++ student, I would first ask, why you use new and a may be "naked" pointer member variably anyway. A First choice would be to create a member variable of type Argument and skip explicit heap allocation. If you really need dynamic allocation in modern code I'd recommend to use shared_ptr<Argument> and Function::Function():m_pxArgument(make_shared()){}

The second question I would like to ask, is why you want to translate std::bad_alloc to your own exception type and if that needs to be done in the constructor. std::bad_alloc is standardized exception for the situation that you actually encounter and if that happens, live is usually bad enough that your little process can not do much to recover (see the pattern "Captain Oates" by Charles Weir and James Noble).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top