gpt4 book ai didi

c++ - Gtest : capture output but print it on failure

转载 作者:行者123 更新时间:2023-11-30 01:16:06 24 4
gpt4 key购买 nike

因此,我有一个将消息打印到 coutcerr 的类。可悲的是,重构它以使用日志记录是不可能的。在我的测试中,我想同时捕获 coutcerr,就像 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 方法,但我仍然缺少故障检查。

最佳答案

您需要实现自定义测试监听器并使用它。你可以看看我是如何实现自定义监听器的 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;
}
}
};

关于c++ - Gtest : capture output but print it on failure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27274095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com