user1306239
user1306239

Reputation: 13

Extremely simple test library

Is there easily embeddable C++ test lib with a friendly license? I would like a single header file. No .cpp files, no five petabytes of includes. So CppUnit and Boost.Test are out.

Basically all I want is to drop single file to project tree, include it and be able to write

 testEqual(a,b)

and see if it fail. I'd use assert, but it doesn't work in non-debug mode and can't print values of a and b, and before rewriting assert I'd rather search existing library.

Upvotes: 1

Views: 211

Answers (2)

Not_a_Golfer
Not_a_Golfer

Reputation: 49187

Try google-test https://github.com/google/googletest/

it's really light weight, cross platform and simple.

Upvotes: 2

Magnus Hoff
Magnus Hoff

Reputation: 22089

I'm tempted to say "write your own", which is what I have done. On the other hand, you might want to reuse what I wrote: test_util.hpp and test_util.cpp. It is straightforward to inline the one definition from the cpp file into the hpp file. MIT lisence. I have also pasted it into this answer, below.

This lets you write a test file like this:

#include "test_util.hpp"

bool test_one() {
    bool ok = true;

    CHECK_EQUAL(1, 1);

    return ok;
}

int main() {
    bool ok = true;

    ok &= test_one();

    // Alternatively, if you want better error reporting:
    ok &= EXEC(test_one);

    // ...

    return ok ? 0 : 1;
}

Browse around in the tests directory for more inspiration.


// By Magnus Hoff, from http://stackoverflow.com/a/9964394

#ifndef TEST_UTIL_HPP
#define TEST_UTIL_HPP

#include <iostream>

// The error messages are formatted like GCC's error messages, to allow an IDE
// to pick them up as error messages.
#define REPORT(msg) \
    std::cerr << __FILE__ << ':' << __LINE__ << ": error: " msg << std::endl;

#define CHECK_EQUAL(a, b) \
    if ((a) != (b)) { \
        REPORT( \
            "Failed test: " #a " == " #b " " \
            "(" << (a) << " != " << (b) << ')' \
        ) \
        ok = false; \
    }

static bool execute(bool(*f)(), const char* f_name) {
    bool result = f();
    if (!result) {
        std::cerr << "Test failed: " << f_name << std::endl;
    }
    return result;
}

#define EXEC(f) execute(f, #f)

#endif // TEST_UTIL_HPP

Upvotes: 2

Related Questions