[英]Google Test C++: Is there a way to read the current console output in a test?
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. 现在,在我的Google测试中,我想验证此输出是否已完成。 What would be the lastConsoleOutput equivalent be as used in my pseudo code below? 在下面的伪代码中使用的lastConsoleOutput等效项是什么?
// Tests if sayHello() outputs Hello
TEST(MyClassTest, sayHello)\
{
EXPECT_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. 在这种情况下,我将避免重定向或测试stdout或stderr中的值,因为对这些流的访问不是线程安全的,因此可能不会像预期的那样附加和刷新输出缓冲区。
From a testing perspective I would suggest refactoring the method to be stateless and keep the state (aka std::cout) somewhere else. 从测试的角度来看,我建议将方法重构为无状态,并将状态(aka std :: cout)保留在其他位置。 In your example you start testing behavior of an external API and not the actual modification in your object. 在您的示例中,您将开始测试外部API的行为,而不是对象中的实际修改。
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. 我避免使用类似您的sayHello()
方法的代码。 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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.