Gtest:捕获输出,但在失败时打印
Gtest: capture output but print it on failure
所以,我有一个将消息打印到cout
和cerr
的类。 可悲的是,重构它以使用日志记录是不可能的。在我的测试中,我想同时捕获cout
和cerr
就像这个答案中描述的那样。 如果测试成功,我真的不在乎打印什么。 但是,如果测试失败,我希望看到输出。 所以,我想要的是类似于:
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;
}
}
显然,我可以使用夹具和设置/拆卸方法,但仍然缺少故障检查。
您需要实现一个自定义测试侦听器,并使用它。您可以在此处查看我如何实现自定义侦听器。
在您的情况下,如果您只想打印错误消息,而没有别的,那么这样的事情应该可以工作:
#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;
}
}
};
这是我
使用 BЈовић 的答案想出来的。
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;
};
相关文章:
- 如何循环打印顶点结构
- 如果没有malloc,链表实现将失败
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 如何在c++中打印目录
- 视图中的参数推导失败:take_while
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 如何使"static_assert"打印失败时获得的值?
- 自动打印出哪个 EXPECT 语句失败
- 简单的2D数组标头文件,打印失败
- 打印运算符过载失败
- C GTEST在测试结束时仅在测试失败时打印其他信息
- AudioOutputUnitStart 失败,OSStatus = -66637(如何从 c++ 打印 OSStatu
- Gtest:捕获输出,但在失败时打印
- 打印存储在Iterator中的内容失败
- 如果在谷歌测试中测试失败,如何打印一些东西
- 尝试打印矢量时lldb断言失败
- 为什么打印对象失败并显示"no match for 'operator<<'"错误?