unit test using gtest 1.6 : how to check what is printed out?

做~自己de王妃 提交于 2019-12-07 13:04:51

问题


How do i check a void function that print out sth to the command line?

For example:

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

and then in the test.cpp i put this test case:

TEST(test_printFoo, printFoo) {

    //what do i write here??

}

please explain clearly as i'm new to unit testing and gtest. Thank you


回答1:


You will have to change your function to make it testable. The easiest way to do this is to pass in an ostream ( which cout inherits ) to the function, and use a string stream ( also inherits ostream ) in your unit tests.

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" );
}


来源:https://stackoverflow.com/questions/18908923/unit-test-using-gtest-1-6-how-to-check-what-is-printed-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!