【问题标题】:unit test using gtest 1.6 : how to check what is printed out?使用 gtest 1.6 进行单元测试:如何检查打印的内容?
【发布时间】:2013-09-20 04:40:42
【问题描述】:

我如何检查一个将某物打印到命令行的 void 函数?

例如:

void printFoo() {
                 cout << "Successful" < endl;
             }

然后我在 test.cpp 中放了这个测试用例:

TEST(test_printFoo, printFoo) {

    //what do i write here??

}

请解释清楚,因为我是单元测试和 gtest 的新手。谢谢

【问题讨论】:

    标签: c++ unit-testing googletest


    【解决方案1】:

    您必须更改您的函数以使其可测试。最简单的方法是将 ostream(cout 继承)传递给函数,并在单元测试中使用字符串流(也继承 ostream)。

    void printFoo( std::ostream &os ) 
    {
      os << "Successful" << endl;
    }
    
    TEST(test_printFoo, printFoo) 
    {
      std::ostringstream output;
    
      printFoo( output );
    
      // Not that familiar with gtest, but I think this is how you test they are 
      // equal. Not sure if it will work with stringstream.
      EXPECT_EQ( output, "Successful" );
    
      // For reference, this is the equivalent assert in mstest
      // Assert::IsTrue( output == "Successful" );
    }
    

    【讨论】:

    • 你的意思可能是os &lt;&lt; "Successful" &lt; endl;
    • EXPECT_EQ 中的输出需要调用.str() 来与字符串“Successful”进行比较,例如EXPECT_EQ( output.str(), "Successful" );
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多