如何捕获stdout / stderr与googletest? [英] How to capture stdout/stderr with googletest?

查看:267
本文介绍了如何捕获stdout / stderr与googletest?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 googletest 框架时,是否可以捕获stdout和stderr?

Is it possible to capture the stdout and stderr when using the googletest framework?

例如,我想调用一个函数将错误写入控制台(stderr)。
现在,当调用测试中的函数时,我想断言没有输出。

For example, I would like to call a function that writes errors to the console (stderr). Now, when calling the function in the tests, I want to assert that no output appears there.

或者,我想测试错误行为,

Or, maybe I want to test the error behaviour and want to assert that a certain string gets printed when I (deliberately) produce an error.

推荐答案

我之前使用过这个代码片段测试输出时将cout调用重定向到字符串流。希望它可能会引发一些想法。我从来没有使用googletest。

I have used this snippet before to redirect cout calls to a stringstream when testing output. Hopefully it might spark some ideas. I've never used googletest before.

// This can be an ofstream as well or any other ostream
std::stringstream buffer;

// Save cout's buffer here
std::streambuf *sbuf = std::cout.rdbuf();

// Redirect cout to our stringstream buffer or any other ostream
std::cout.rdbuf(buffer.rdbuf());

// Use cout as usual
std::cout << "Hello World";

// When done redirect cout to its old self
std::cout.rdbuf(sbuf);

在重定向回原始输出之前,使用google测试检查缓冲区中的输出。

Before redirecting back to the original output use your google test to check the output in buffer.

这篇关于如何捕获stdout / stderr与googletest?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆