How to capture stdout/stderr with googletest?

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

    Based on the answer of Wgaffa I made this helper class which can be constructed with either std::cout or std::cerr:

    class CaptureHelper
    {
    public:
      CaptureHelper(std::ostream& ioStream)
        : mStream(ioStream),
        mIsCapturing(false)
      { }
    
      ~CaptureHelper()
      {
        release();
      }
    
      void capture()
      {
        if (!mIsCapturing)
        {
          mOriginalBuffer = mStream.rdbuf();
          mStream.rdbuf(mRedirectStream.rdbuf());
          mIsCapturing = true;
        }
      }
    
      std::string release()
      {
        if (mIsCapturing)
        {
          std::string wOutput = mRedirectStream.str();
          mStream.rdbuf(mOriginalBuffer);
          mIsCapturing = false;
          return wOutput;
        }
      }
    
    private:
      std::ostream& mStream;
      bool mIsCapturing;
      std::stringstream mRedirectStream;
      std::streambuf* mOriginalBuffer;
    
    };
    

提交回复
热议问题