Search code examples
c++boostboost-test

What is the better way to generate test report in a file using BOOST.Test?


I know by default report is directed to standard-error, and so one has to redirect it to a file. My question is shall we do this inside a global fixture? Which isn't seem to be working for me some how.

This is what i tried -

struct MyConfig
{
 MyConfig()
  : testReport("fileName.log")
  {
    if(!testReport.fail())
     original = std::cerr.rdbuf(testReport.rdbuf());
  }
  ~MyConfig()
    {        
        cerr.rdbuf(original);        
        testReport.close();
    }
    ofstream testReport;
    streambuf* original;

 };

 BOOST_GLOBAL_FIXTURE(MyConfig);

After running the test, report outputs on console only, though a 0kb file is created with the given name.


Solution

  • You could try this alternative, adapted from here and alleged to work on Boost 1.34.1. This seems to be more as Boost intends - see the usage of a results stream overrider.

    //
    // run_tests.cc
    //
    
    #define BOOST_AUTO_TEST_MAIN
    
    #include <iostream>
    #include <fstream>
    #include <cassert>
    #include <boost/test/auto_unit_test.hpp>
    #include <boost/test/results_reporter.hpp>
    
    std::ofstream ReportRedirector::out;
    
    struct ReportRedirector
    {
        ReportRedirector()
        {
            out.open("fileName.log");
            assert( out.is_open() );
            boost::unit_test::results_reporter::set_stream(out);
        }
    private:
        static std::ofstream out;
    };
    
    BOOST_GLOBAL_FIXTURE(ReportRedirector)