Visual Assert – The Unit Testing Add-In for Visual C++
cfix – C/C++ Unit Testing for Win32 and NT
 
 

Exceptions

Exceptions

C++ code frequently makes use of exceptions, so it makes sense to write tests that check whether the right exceptions are thrown. For this purpose, cfix provides CFIXCC_METHOD_EXPECT_EXCEPTION.

To illustrate how CFIXCC_METHOD_EXPECT_EXCEPTION is used, we add another method to our fixture, TestThatThrows:

#include <cfixcc.h>
#include <bitset>

class ExampleTest : public cfixcc::TestFixture
{
public:
  void TestOne() 
  {
    // As before.
  }
  
  void TestTwo() 
  {
    // As before.
  }
  
  void TestThatThrows()
  {
    std::bitset< 33 > bitset;
    bitset[ 32 ] = 1;
    bitset.to_ulong();	// Will throw an std::overflow_error.
  }
};

CFIXCC_BEGIN_CLASS( ExampleTest )
  CFIXCC_METHOD( TestOne )
  CFIXCC_METHOD( TestTwo )
  CFIXCC_METHOD_EXPECT_EXCEPTION( TestThatThrows, std::overflow_error )
CFIXCC_END_CLASS()
			

TestThatThrows should lead to an std::overflow_error being raised and by using CFIXCC_METHOD_EXPECT_EXCEPTION, we check that this is indeed the case.

Running the suite again should now yield the following output, indicating that all tests succeeded:

[Success]      VsSample.ExampleTest.TestOne
[Success]      VsSample.ExampleTest.TestTwo
[Success]      VsSample.ExampleTest.TestThatThrows
			

Back to TestThatThrows, we now modify the code so that the exception is not raised any more:

  void TestThatThrows()
  {
    std::bitset< 33 > bitset;
    bitset[ 32 ] = 0;	
    bitset.to_ulong();	// No overflow here.
  }
			

Indeed, if we now run the test again, we get the following output:

[Success]      VsSample.ExampleTest.TestOne
[Success]      VsSample.ExampleTest.TestTwo
[Failure]      VsSample.ExampleTest.TestThatThrows
                 Expression: Expected exception, but none has been raised
                 
                 [...]