How to capture stdout/stderr with googletest?

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

    We are doing exactly what you are referring to.

    First we created some macros:

        #define CAPTURE_STDOUT StdoutRedirect::instance().redirect();
        #define RELEASE_STDOUT StdoutRedirect::instance().reset();
        #define ASSERT_INFO( COUNT, TARGET )   \
          ASSERT_PRED_FORMAT2(OurTestPredicates::AssertInfoMsgOutput, TARGET, COUNT );
    

    See this answer for capturing stdout and stderr: https://stackoverflow.com/a/5419409/9796918 Just use their BeginCapture(), EndCapture() in place of our redirect() and reset().

    In the AssertInfoMsgOutput method:

        AssertionResult OurTestPredicates::AssertInfoMsgOutput( const char* TARGET,
            const char* d1,
            const char* d2,
            int         COUNT )
        {
          int count = 0;
          bool match = false;
          std::string StdOutMessagge = GetCapture();
          // Here is where you process the stdout/stderr info for the TARGET, and for
          // COUNT instances of that TARGET message, and set count and match
          // appropriately
          ...
          if (( count == COUNT ) && match )
          {
            return ::testing::AssertionSuccess();
          }
          return :: testing::AssertionFailure() << "not found";
        }
    

    Now in your unit test just wrap your calls that you want to capture stdout/stderr with:

        CAPTURE_STDOUT
        // Make your call to your code to test / capture here
        ASSERT_INFO( 1, "Foo bar" );
        RELEASE_STDOUT
    

提交回复
热议问题