使用gtest进行单元测试1.6:如何查看打印出来的内容?

时间:2013-09-20 04:40:43

标签: c++ unit-testing googletest

如何检查打印出命令行的void函数?

例如:

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

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

TEST(test_printFoo, printFoo) {

    //what do i write here??

}

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

1 个答案:

答案 0 :(得分:6)

您必须更改功能才能使其可测试。最简单的方法是将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" );
}