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 (
Putting Wgaffa's suggestion (which I like) to a Google Test fixture, one might write:
namespace {
class MyTestFixture : public ::testing::Test {
protected:
MyTestFixture() : sbuf{nullptr} {
// intentionally empty
}
~MyTestFixture() override = default;
// Called before each unit test
void SetUp() override {
// Save cout's buffer...
sbuf = std::cout.rdbuf();
// Redirect cout to our stringstream buffer or any other ostream
std::cout.rdbuf(buffer.rdbuf());
}
// Called after each unit test
void TearDown() override {
// When done redirect cout to its old self
std::cout.rdbuf(sbuf);
sbuf = nullptr;
}
// The following objects can be reused in each unit test
// This can be an ofstream as well or any other ostream
std::stringstream buffer{};
// Save cout's buffer here
std::streambuf *sbuf;
};
TEST_F(MyTestFixture, StackOverflowTest) {
std::string expected{"Hello"};
// Use cout as usual
std::cout << expected;
std::string actual{buffer.str()};
EXPECT_EQ(expected, actual);
}
} // end namespace