3

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

例如:

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

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

TEST(test_printFoo, printFoo) {

    //what do i write here??

}

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

4

1 回答 1

8

您将不得不更改您的功能以使其可测试。最简单的方法是将 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" );
}
于 2013-09-20T04:55:48.373 回答