Boost unit test example

Tags:

#include <iostream>
#include <boost/test/unit_test.hpp>

// Note that the following header is needed!!!
// Without this, you must compile like: 
// g++ -lboost_unit_test_framework foo.cpp
#include <boost/test/included/unit_test_framework.hpp> 

using namespace std;
using namespace boost;
using namespace boost::unit_test;

struct NumAnalyzer
{
    bool isOdd(unsigned val) { return (val % 2); }
    bool isEven(unsigned val) { return !(val % 2); }
};

class TestNumAnalyzer
{
    NumAnalyzer _analyzer;

public:
    void test_isOdd()
    {
        BOOST_REQUIRE(_analyzer.isOdd(3) == true);
        BOOST_REQUIRE(_analyzer.isOdd(4) == false);
    }

    void test_isEven()
    {
        BOOST_REQUIRE(_analyzer.isEven(3) == false);
        BOOST_REQUIRE(_analyzer.isEven(4) == true);
    }
};

class TestSuiteNumAnalyzer: public test_suite
{
public:
    TestSuiteNumAnalyzer(): test_suite("test_suite_num_analyzer")
    {
        shared_ptr<TestNumAnalyzer> instance(new TestNumAnalyzer());
        test_case *isOdd = BOOST_CLASS_TEST_CASE(
            &TestNumAnalyzer::test_isOdd, instance);
        test_case *isEven = BOOST_CLASS_TEST_CASE(
            &TestNumAnalyzer::test_isEven, instance);

        add(isOdd);
        add(isEven);
    }
};

test_suite* init_unit_test_suite(int argc, char** argv)
{
    test_suite* suite(BOOST_TEST_SUITE("Master Suite"));
    suite->add(new TestSuiteNumAnalyzer());
    return suite;
}