2014-12-03 167 views
1

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

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

显然,我可以用一个夹具并为此设置/ TearDown中的方法,但我仍然失踪的故障检查。

回答

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

非常好!这让我想出了一些东西。 – Sardathrion 2014-12-03 15:02:00

+1

@Sardathrion也看看这个:https://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Defining_Event_Listeners – 2014-12-03 15:04:11

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