Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I check my program's output with boost test?

Like in:

void f()
{
  cout << "blah" << endl;
}

BOOST_AUTO_TEST_CASE(f)
{
  f();
  // This would be a beauty
  // BOOST_CHECK_PROGRAM_OUTPUT_MATCH("blah");
}
like image 622
rturrado Avatar asked Mar 23 '11 12:03

rturrado


People also ask

What is boost unit testing?

The Boost Test Library's Unit Test Framework is designed to automate those tasks. The library supplied main() relieves users from messy error detection and reporting duties. Users could use supplied testing tools to perform complex validation tasks.

How do I run a unit test boost Visual Studio?

Create a Boost. cpp file for your tests, right-click on the project node in Solution Explorer and choose Add > New Item. In the Add New Item dialog, expand Installed > Visual C++ > Test. Select Boost. Test, then choose Add to add Test.


2 Answers

Yes, you can do it by redirecting std::cout to a boost::test_tools::output_test_stream, which provides special methods to compare the output. To make sure std::cout is always restored correctly, you can use a custom struct, like shown in the following example.

#define BOOST_TEST_MAIN

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

BOOST_AUTO_TEST_SUITE( TestSuite1 )

struct cout_redirect {
    cout_redirect( std::streambuf * new_buffer ) 
        : old( std::cout.rdbuf( new_buffer ) )
    { }

    ~cout_redirect( ) {
        std::cout.rdbuf( old );
    }

private:
    std::streambuf * old;
};

BOOST_AUTO_TEST_CASE( test1 )
{
    boost::test_tools::output_test_stream output;
    {
        cout_redirect guard( output.rdbuf( ) );

        std::cout << "Test" << std::endl;
    }

    BOOST_CHECK( output.is_equal( "Test\n" ) );
}

BOOST_AUTO_TEST_SUITE_END()
like image 65
Björn Pollex Avatar answered Sep 28 '22 02:09

Björn Pollex


I have followed @Björn Pollex 's answer for some days. But one day I found that it's not necessary to do it like that. Just use boost::test_tools::output_test_stream.

#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/test/output_test_stream.hpp>

BOOST_AUTO_TEST_SUITE(TestSuite1)

BOOST_AUTO_TEST_CASE(test1)
{
    boost::test_tools::output_test_stream output;
    output << "Test";

    BOOST_CHECK(output.is_equal("Test"));
}

BOOST_AUTO_TEST_SUITE_END()

For more information, read the official documentation.

like image 38
Hank Avatar answered Sep 28 '22 02:09

Hank