Deqing
Deqing

Reputation: 14632

How to reuse test case in Boost test framework?

For example I have following test case:

#include <MyClass.hpp>
#define BOOST_TEST_MODULE MyTest
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE( my_test )
{
    MyClass o1(42), o2(21);
    BOOST_CHECK( o1.is_valid() );
    BOOST_CHECK_EQUAL( o1 == o2 * 2 );
    BOOST_CHECK_EQUAL ...
    ...
}

There are several similar classes that had implemented same methods, would like to test them by the same logic, test cases might be like following:

BOOST_AUTO_TEST_CASE( my_test1 )
{
    MyClass1 o1(42), o2(21);
    BOOST_CHECK( o1.is_valid() );
    BOOST_CHECK_EQUAL( o1 == o2 * 2 );
    BOOST_CHECK_EQUAL ...
    ...
}

BOOST_AUTO_TEST_CASE( my_test2 )
{
    MyClass2 o1(42), o2(21);
    BOOST_CHECK( o1.is_valid() );
    BOOST_CHECK_EQUAL( o1 == o2 * 2 );
    BOOST_CHECK_EQUAL ...
    ...
}

BOOST_AUTO_TEST_CASE( my_test3 )
{
    MyClass3 o1(42), o2(21);
    BOOST_CHECK( o1.is_valid() );
    BOOST_CHECK_EQUAL( o1 == o2 * 2 );
    BOOST_CHECK_EQUAL ...
    ...
}

...

Is there a way to reuse logic in the test case?

Upvotes: 3

Views: 183

Answers (1)

kersson
kersson

Reputation: 23

Check out template test cases.

#include <MyClass.hpp>    
#define BOOST_TEST_MODULE MyTest
#include <boost/test/included/unit_test.hpp>
#include <boost/mpl/list.hpp>

typedef boost::mpl::list<MyClass1,MyClass2,MyClass3> test_types;

BOOST_AUTO_TEST_CASE_TEMPLATE( my_test, T, test_types )
{
    T o1(42), o2(21);
    BOOST_CHECK( o1.is_valid() );
    BOOST_CHECK_EQUAL( o1 == o2 * 2 );
    BOOST_CHECK_EQUAL ...
    ...
}

Upvotes: 1

Related Questions