Is it possible to capture the stdout and stderr when using the googletest framework?
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.
Googletest offers functions for this:
Avoiding having to do this is always a good design idea. If you really want to do it the following works:
To use stderr instead of stdout change the second argument to dup2 to be 2. For capturing without going via a file you could use a pipe pair instead.
Rather than do this, use dependency injection to remove the direct use of
std::cout
. In your test code use a mock object of classstd:ostringstream
as a mock object instead of the realstd::cout
.So instead of this:
have this:
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.
Before redirecting back to the original output use your google test to check the output in buffer.