How to capture stdout/stderr with googletest?

后端 未结 7 2068
心在旅途
心在旅途 2020-12-12 20:18

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 (

相关标签:
7条回答
  • 2020-12-12 21:23

    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.

    0 讨论(0)
提交回复
热议问题