Reputation: 1426
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
Upvotes: 3
Views: 5045
Reputation: 966
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" );
}
Upvotes: 8