I’ve been trying to find a decent unit testing framework for C++. My main requirements:
As the test writer, you should have to write as little code as possible in order to get keep the framework happy.
No external tools needed, or libraries to link to, if possible. I’m not against dependencies, but I’d like to use the framework anywhere there’s a C++ compiler.
It should be possible to run the tests in a variety of ways, i.e. you can just grab the built test suite and run it with whatever front end you fancy.
Liberal license. I like the MIT license, myself, but anything close is ok.
After I’d hacked something up myself, I was pointed to tut, which looks quite decent. It does everything with templates, which is cleaner than my cpp stuff. I’m no template guru, though, so I couldn’t figure out how to give names to tests. With tut, tests are numbered, which looks a bit annoying. Test 6 failed? What was test 6?
I carried on with my own hacked up framework, which seems to be approximately complete now. I’ll ask the tut author if he knows whether it’ll be possible to add names to tests, and to compile all the tests into a shared library for running with a separate front-end.
Quick attempt at framework may be found
here.
With my framework, tests look like this:
#include "UnitTest.h"
#include "BankAccount.h"
UNIT_TESTS
TEST_DATA(BankAccount)
BankAccount account;
TEST_END_DATA(BankAccount)
TEST_SET_UP(BankAccount)
{
account.setBalance(3);
}
TEST_TEAR_DOWN(BankAccount)
{
account.setBalance(0);
}
TEST(BankAccount, InitialBalance)
{
ASSERT_EQUAL(account.balance(), 3);
}
TEST(BankAccount, Credit)
{
account.credit(100);
ASSERT_EQUAL(account.balance(), 103);
}
TEST(BankAccount, Debit)
{
account.debit(100);
ASSERT_EQUAL(account.balance(), -97);
}
TEST(BankAccount, Bogus)
{
account.debit(100);
ASSERT_EQUAL(account.balance(), -10000);
}
There are console-based and Qt-based test runners. The Qt version isn’t quite complete yet. It needs to show what went wrong in which test, and allow navigating to the source position, but it shows the general idea of what I’m trying to do.