Search code examples
c++unit-testingboostboost-test

Boost unit test in separate cpp files


I want to separate my Boost unit tests into separate .cpp files (e.g. Test1.cpp, Test2.cpp, Test3.cpp ... etc) So that I do not have 1000 tests in a single cpp file. So far I have been getting all kinds of errors when I try to build.

Test1.cpp

#define BOOST_TEST_MODULE MasterTestSuite
#include <boost/test/included/unit_test.hpp>
BOOST_AUTO_TEST_CASE(myTestCase)
{
  BOOST_CHECK(1 == 1);  
}

Test2.cpp

#define BOOST_TEST_MODULE MasterTestSuite2
#include <boost/test/included/unit_test.hpp>
BOOST_AUTO_TEST_CASE(myTestCase2)
{
  BOOST_CHECK(2 == 2);  
}

Solution

  • boost-test generates it's own main function when you define BOOST_TEST_MODULE, see: BOOST_TEST_MODULE. Some of your errors are likely to be because of this.

    I put BOOST_TEST_MODULE in a separate file, e.g.:

    test_main.cpp

    #ifndef _MSC_VER
    #define BOOST_TEST_DYN_LINK
    #endif
    #define BOOST_TEST_MAIN
    #define BOOST_TEST_MODULE Main
    #include <boost/test/unit_test.hpp>
    

    And then use test suites to separate unit tests into separate .cpp files, with a test suite in each unit test file e.g.:

    Test1.cpp

    #include <boost/test/unit_test.hpp>
    
    BOOST_AUTO_TEST_SUITE(MyTests)
    
    BOOST_AUTO_TEST_CASE(myTestCase)
    {
      BOOST_CHECK(1 == 1);
    }
    
    BOOST_AUTO_TEST_SUITE_END()
    

    Test2.cpp

    #include <boost/test/unit_test.hpp>
    
    BOOST_AUTO_TEST_SUITE(MyTests2)
    
    BOOST_AUTO_TEST_CASE(myTestCase2)
    {
      BOOST_CHECK(2 == 2);
    }
    
    BOOST_AUTO_TEST_SUITE_END()
    

    You can find an example of this approach in the tests directory here.