Gtest:捕获输出,但在失败时打印



所以,我有一个将消息打印到coutcerr的类。 可悲的是,重构它以使用日志记录是不可能的。在我的测试中,我想同时捕获coutcerr就像这个答案中描述的那样。 如果测试成功,我真的不在乎打印什么。 但是,如果测试失败,我希望看到输出。 所以,我想要的是类似于:

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;
};

最新更新