How to capture stdout/stderr with googletest?

后端 未结 7 2074
心在旅途
心在旅途 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条回答
  •  Happy的楠姐
    2020-12-12 21:15

    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
    
    

提交回复
热议问题