Google Test C++:有没有办法在测试中读取当前控制台输出?
让我们假设我有一个要测试的类,它具有以下方法:
void
MyClass::sayHello()
{
std::cout << "Hello";
}
现在,在我的谷歌测试中,我想验证是否已生成此输出。下面我的伪代码中使用的 lastConsoleOutput 等效项是什么?
// Tests if sayHello() outputs Hello
TEST(MyClassTest, sayHello)\
{
EXPECT_EQ(lastConsoleOutput,"Hello");
}
感谢您的任何反馈!
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)\
{
EXPECT_EQ(lastConsoleOutput,"Hello");
}
Thank you for any feedback!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,我将避免重定向或测试 stdout 或 stderr 中的值,因为对这些流的访问不是线程安全的,输出缓冲区可能不会像可能预测的那样被附加和刷新。
从测试的角度来看,我建议将该方法重构为无状态并将状态(又名 std::cout)保留在其他地方。在您的示例中,您开始测试外部 API 的行为,而不是对象中的实际修改。
在您的测试代码中,您现在可以使用以下命令轻松执行测试
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.
In your testing code you can now easily perform the test using
我避免使用类似
sayHello()
方法的代码。我会将其重构为:那么测试方法将如下所示:
I avoid having code like your
sayHello()
method. I would refactor it to something like:Then the test method would be like this: