所以,我有一个类将消息打印到cout
和cerr
。遗憾的是,重构它以使用日志记录是不可能的。在我的测试中,我想同时捕获cout
和cerr
,就像described in this answer一样。如果测试成功,我真的不在乎打印什么。但是,如果测试失败,我想看看输出。所以,我想要的是类似于:
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;
}
}
显然,我可以使用夹具和SetUp / TearDown方法,但仍然缺少故障检查。
答案 0 :(得分:3)
class TestOOK : public ::testing::Test
{
protected:
virtual void SetUp()
{
buffer.str( std::string() ); // clears the buffer.
sbuf = std::cout.rdbuf();
std::cout.rdbuf( buffer.rdbuf() );
}
virtual void TearDown()
{
std::cout.rdbuf( sbuf );
const ::testing::TestInfo* const test_info =
::testing::UnitTest::GetInstance()->current_test_info();
if ( test_info->result()->Failed() )
{
std::cout << std::endl << "Captured output from "
<< test_info->test_case_name()
<< " is:"
<< std::endl
<< buffer.str()
<< std::endl;
}
}
std::stringstream buffer;
std::streambuf* sbuf;
};
答案 1 :(得分:2)
您需要实现自定义测试侦听器并使用它。您可以查看我如何实现自定义侦听器here。
在您的情况下,如果您只想打印错误消息,而不是其他任何内容,那么这样的事情应该有效:
#include "gtest/gtest.h"
class MyTestPrinter : public ::testing::EmptyTestEventListener
{
virtual void OnTestEnd( const ::testing::TestInfo& test_info )
{
if ( test_info.result()->Failed() )
{
std::cout << test_info.test_case_name() << " failed " << test_info.name() << std::endl;
}
}
};