How to capture stdout/stderr with googletest?

后端 未结 7 2078
心在旅途
心在旅途 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:07

    Rather than do this, use dependency injection to remove the direct use of std::cout. In your test code use a mock object of class std:ostringstream as a mock object instead of the real std::cout.

    So instead of this:

     void func() {
        ...
        std::cout << "message";
        ...
     }
    
     int main (int argc, char **argv) {
        ...
        func();
        ...
     }
    

    have this:

     void func(std::ostream &out) {
        ...
        out << "message";
        ...
     }
    
     int main(int argc, char **argv) {
        ...
        func(std::cout);
        ...
     }
    

提交回复
热议问题