【问题标题】:Gtest: capture output but print it on failureGtest:捕获输出但在失败时打印
【发布时间】:2015-02-01 03:44:52
【问题描述】:

所以,我有一个向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 方法,但仍然缺少故障检查。

【问题讨论】:

    标签: c++ googletest


    【解决方案1】:

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

    【讨论】:

    【解决方案2】:

    这是我使用BЈовићanswer 想到的。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-02
      • 1970-01-01
      相关资源
      最近更新 更多