Like in:
void f()
{
cout << "blah" << endl;
}
BOOST_AUTO_TEST_CASE(f)
{
f();
// This would be a beauty
// BOOST_CHECK_PROGRAM_OUTPUT_MATCH("blah");
}
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With