There have been many C/C++ unit testing tools over the years, from CppUnit and CppTestKit (which seems to have disappeared from the web) to Google Test and CppUTest. I’ve tried many of these, but not all of them.
Lately, I’ve tended to prefer one called UnitTest++. It has the basic features I need without a lot of tedious bookkeeping to do. For example, CppUnit used to require three different changes for each new test method. I haven’t used it in a long time, so I’m not sure if it still does.
UnitTest++ doesn’t change much these days, but it’s still quite effective.
Here’s a minimal C++ program that runs a failing test:
As you can see, a simple test method uses the
TEST macro to define
and register the test.
If you want to share setup and teardown between tests, you can create
a simple fixture
class and the
The thing I really like about the TEST_FIXTURE macro is that the test is actually a method on (a subclass of) the Fixture class, so you can directly reference instance variables and methods defined on the fixture class.
It’s also really easy to create multiple fixtures in a file and use the appropriate fixture for each test. In this way, you can do something similar to RSpec’s nested contexts.
There’s support for test suites, which put your tests into different
RunAllTests() can also be called for a specific suite
name if you want to focus on a particular group of tests.
UnitTest++ has the usual assortment of
CHECK_* macros, and you can
also write your own.
There are a number of different reporters that can be plugged in, so you can report test results to stdout, or as XML to a file that can be used by a CI system like Jenkins.
Overall, I’ve been pretty happy with UnitTest++ and I look forward to using it more.
One note of caution, though: A co-worker recently tried to use it on a project where he was also playing with Google Mock, and he found that there were some macro name collisions involved. I haven’t had a chance to investigate his report yet, but if you use Google Mock, you might want to be careful.
Update: I finally had a chance to dig into this problem, and the
conflict is with the
TEST macro. Google Mock pulls in Google Test
even if you’re not using the latter, and both Google Test and
UnitTest++ define that macro. If you define
GTEST_DONT_DEFINE_TEST=1, you can get around this conflict. We
added that to our compiler command line, but you could also simply
#define it in your code just before including the Google Mock