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

hyd*_*don 3 c++ unit-testing googletest

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

例如:

void printFoo() {
                 cout << "Successful" < endl;
             }
Run Code Online (Sandbox Code Playgroud)

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

TEST(test_printFoo, printFoo) {

    //what do i write here??

}
Run Code Online (Sandbox Code Playgroud)

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

Kin*_*ead 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" );
}
Run Code Online (Sandbox Code Playgroud)

  • EXPECT_EQ 中的输出需要调用 `.str()` 来与字符串 "Successful" 进行比较,例如 `EXPECT_EQ( output.str(), "Successful" );` (3认同)