Writing your first unittest - Nachtfeuer/concept-cpp GitHub Wiki

Writing a first test suite works like this:

#include <unittest/unittest.h>

using namespace unittest;
using namespace matcher;

describe_suite("My first suite", [](){
   describe_test("My first test", []() {
        assert_that(true, is_equal(true));
    });
});

You can create on suite per file only. Each describe create a suite class for given name (which has to be unique) and executes immediately the suite function. By executing of it each describe of a test registers the test function for given test name (which has to be unique in context of current suite) but execution of the test will be triggered by the runner (see below).

The next code is to create the application for your test suites:

#include <unittest/runner.h>

int main(int argc, char* argv[]) {
    if (!unittest::runner::get().run(argc, argv)) {
        return 1;
    }
    return 0;
}

The runner does hierarchical iterate to each registered suite and each suite does iterate to the registered tests executing its functions which finally leads to the assertion checks.

That' all. You have to link the libboost_program_options to your application. If you also use cmake then check the CMakeList.txt in this project on how to do this.

Let's say you application binary name is mytests then you can do following with it:

$ ./mytests --help
options:
  --help                    print this help
  --shuffle-suites arg (=0) running registered suites in random order otherwise
                            sorted by name.
  --shuffle-tests arg (=0)  running registered tests per suite in random order 
                            otherwise sorted by name.
  --filter arg              filtering for individual unittests that are 
                            executed
  --format arg (=default)   output format for unit tests results (default: 
                            internal format)

If you run it without parameters:

Finished suite 'My first suite'
  ... test 'My first test' (0.003282ms) [succeeded]

All 1 tests have passed!

The options are for some obviosue purposes:

  • shuffle should help to detect problems with cleanup (one test should not depend on another).
  • filter is too execute and see suites only fitting to this filter.
  • format is to be able to generate the TAP format (useful for Jenkins)