unit test using gtest 1.6 : how to check what is p

2019-05-10 03:41发布

问题:

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