Let us assume I have a to be tested class that has the following method:
void
MyClass::sayHello()
{
std::cout << "Hello";
}
Now, within my google test I would like to verify that this output has been made. What would be the lastConsoleOutput equivalent be as used in my pseudo code below?
// Tests if sayHello() outputs Hello
TEST(MyClassTest, sayHello)\
{
EXPEC开发者_如何学PythonT_EQ(lastConsoleOutput,"Hello");
}
Thank you for any feedback!
In this case I would avoid redirecting or testing for values in stdout or stderr, since the access to those streams is not threads-safe in a way that output buffer may not be appended and flushed as possibly predicted.
From a testing perspective I would suggest refactoring the method to be stateless and keep the state (a.k.a. std::cout) somewhere else. In your example you start testing behavior of an external API and not the actual modification in your object.
class MyClass {
std::sstream state;
public:
void print(){ std::cout << state.str(); } // no need to test this method, only external API
void changeState() {
state << "Hello" << std::endl; // this should be tested
}
}
In your testing code you can now easily perform the test using
// Tests if sayHello() outputs Hello
TEST(MyClassTest, sayHello)
{
myClass.changeState();
EXPECT_STREQ(myClass.state.str().c_str(),"Hello");
}
I avoid having code like your sayHello()
method. I would refactor it to something like:
void MyClass::sayHello(std::ostream& out) {
out << "Hello";
}
Then the test method would be like this:
TEST(MyClassTest, sayHello) {
MyClass c;
std::stringstream strm;
c.sayHello(strm);
EXPECT_STREQ("Hello", strm.str.c_str());
}
精彩评论