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 (
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;
};