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?
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With