So, I have a class that prints messages to cout
and cerr
. Sadly, refactoring it to use logging is out of the question. In my tests, I would like to capture both cout
and cerr
like it is described in this answer. In case the tests succeed, I really do not care what is printed. However, if the tests fail, I would like to see the output. So, what I want is something akin to:
TEST(ook, eek)
{
// Capture cout.
std::stringstream buffer;
std::streambuf *sbuf = std::cout.rdbuf();
std::cout.rdbuf(buffer.rdbuf());
// Do test things:
auto ret = my_weird_function(some, weird, parameters);
EXPECT_TRUE(ret);
// Revert the capture.
std::cout.rdbuf(sbuf);
// Only print if things have gone wrong...
if (ERROR)
{
std::cout << buffer.str() << std::endl;
}
}
Clearly, I could use a fixture and the SetUp/TearDown methods for this but am still missing the failure check.