2014-12-03 169 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; 
};