Can I check my program's output with boost test?
Like in:
void f()
开发者_如何学Go{
cout << "blah" << endl;
}
BOOST_AUTO_TEST_CASE(f)
{
f();
// This would be a beauty
// BOOST_CHECK_PROGRAM_OUTPUT_MATCH("blah");
}
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()
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.
精彩评论