We use Microsoft development tools for much of our work. For an all-native C++ project we recommend their relatively new CppUnitTestFramework. It integrates nicely with Visual Studio and Team Build. Entry points are automatically registered, so you don’t need to keep a running list of unit tests. And it is fast! Our tests average 1 ms each.
However, there is one glaring omission: the test runner does not show the message string from unhandled standard exceptions.
It is common for tests to fail due to exceptions. We take it for granted in our managed tests that we will get some useful information in the failure text.
So we wrote a small extension to unpack the exception message for the test output.
We have the following macros included from stdafx.h so they are readily available.
#define _TEST_METHOD_EX_EXPANDER(_testMethod)
_testMethod { try
// Adds support for seeing std::exception in test output. Requires TEST_METHOD_EX_END after test.
// Example:
// TEST_METHOD_EX_BEGIN(MyFailingTest){ throw std::exception("What happened"); } TEST_METHOD_EX_END;
#define TEST_METHOD_EX_BEGIN(_methodName) _TEST_METHOD_EX_EXPANDER(TEST_METHOD(_methodName))
// Use following test declared with TEST_METHOD_EX_BEGIN
#define TEST_METHOD_EX_END
catch (::std::exception& ex)
{
::std::wstringstream ws; ws << "Unhandled Exception:" << ::std::endl << ex.what();
::Microsoft::VisualStudio::CppUnitTestFramework::Assert::Fail(ws.str().c_str());
}
}
Use it as follows:
TEST_METHOD_EX_BEGIN(ShouldIndicateWhatWentWrong)
{
throw std::exception("The system is down!");
}
TEST_METHOD_EX_END
Clearly, the one downside is the macro at the end of the test. We can only hope that Microsoft incorporates some handling of std::exception in the next release. Until then, we hope you find this useful.