Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How CppUnit implements a test for an exception

Tags:

c++

cppunit

I know that CppUnit makes it possible to test for an exception via:

CPPUNIT_ASSERT_THROW(expression, ExceptionType);

Can anybody explain how CPPUNIT_ASSERT_THROW() is implemented?

like image 713
avinash Avatar asked Apr 23 '10 09:04

avinash


2 Answers

Reporting of test failures in CppUnit is done via throwing of a custom exception type. We'll call that CppUnitException here for simplicity.

CPPUNIT_ASSERT_THROW is a macro that will expand to something that is essentially this:

try
{
   expression;
   throw CppUnitException("Expected expression to throw");
}
catch( const ExceptionType & e )
{
}

If expression throws (as we'd expect it to), we fall into the catch block which does nothing.

If expression does not throw, execution proceeds to the line of code that throws CppUnitException which will trigger a test failure.

Of course, the implementation of the CPPUNIT_ASSERT_THROW macro is actually a bit fancier so that line and file information is also reported, but that is the general gist of how it works.

like image 80
Michael Anderson Avatar answered Sep 28 '22 07:09

Michael Anderson


Edit: I've upvoted Michael Anderson's answer, since he is more specific about the exact code from CppUnit, while mine is a more general answer.

In pseudocode, it'll be something like this:

try
  {
  // Test code that should throw      
  }
catch(ExceptionType e)
  {
  // Correct exception - handle test success
  return; 
  }
catch(...)
  {
  // Wrong exception, handle test failure.
  return;
  }
// No exception, handle test failure.
return;
like image 21
Joris Timmermans Avatar answered Sep 28 '22 06:09

Joris Timmermans