c++unit-testingstdoutstderrgoogletest

How to capture stdout/stderr with googletest?


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.


Solution

  • 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);
    

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