How CppUnit implements a test to exclude

I know that CppUnit allows testing an exception through:

CPPUNIT_ASSERT_THROW(expression, ExceptionType); 

Can someone explain how CPPUNIT_ASSERT_THROW() implemented?

+6
c ++ cppunit
source share
2 answers

Test error reporting in CppUnit is done by throwing a custom exception type on it. We will call this CppUnitException here for simplicity.

CPPUNIT_ASSERT_THROW is a macro that will expand to what it essentially is:

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

If expression throws (as expected), we end up in a catch that does nothing.

If expression not thrown, execution proceeds to a line of code that throws a CppUnitException that will cause the test to fail.

Of course, the implementation of the CPPUNIT_ASSERT_THROW macro is actually a little more interesting, so the line and file information is also reported, but this is the general essence of how it works.

+6
source share

Edit: I confirmed Michael Anderson's answer as it is more specific about the exact code from CppUnit, and mine is a more general answer.

In pseudo code, it will 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; 
+3
source share

All Articles