64

使用googletest框架时是否可以捕获标准输出和标准错误?

例如,我想调用一个将错误写入控制台(stderr)的函数。现在,在测试中调用该函数时,我想断言那里没有输出。

或者,也许我想测试错误行为并想要断言当我(故意)产生错误时会打印某个字符串。

4

7 回答 7

108

Googletest 为此提供了功能:

testing::internal::CaptureStdout();
std::cout << "My test";
std::string output = testing::internal::GetCapturedStdout();
于 2015-10-17T11:41:57.910 回答
37

在测试输出时,我之前使用过此代码段将 cout 调用重定向到字符串流。希望它可以激发一些想法。我以前从未使用过googletest。

// This can be an ofstream as well or any other ostream
std::stringstream buffer;

// Save cout's buffer here
std::streambuf *sbuf = std::cout.rdbuf();

// Redirect cout to our stringstream buffer or any other ostream
std::cout.rdbuf(buffer.rdbuf());

// Use cout as usual
std::cout << "Hello World";

// When done redirect cout to its old self
std::cout.rdbuf(sbuf);

在重定向回原始输出之前,请使用您的谷歌测试检查缓冲区中的输出。

于 2010-10-28T14:23:11.747 回答
7

避免这样做总是一个好的设计理念。如果您真的想这样做,请执行以下操作:

#include <cstdio>
#include <cassert>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <iostream>

int main() {
   int fd = open("my_file.log", O_WRONLY|O_CREAT|O_TRUNC, 0660);
   assert(fd >= 0);
   int ret = dup2(fd, 1);
   assert(ret >= 0);
   printf("This is stdout now!\n");
   std::cout << "This is C++ iostream cout now!" << std::endl;
   close(fd);
}

要使用 stderr 而不是 stdout,请将 dup2 的第二个参数更改为 2。对于不通过文件进行捕获,您可以使用管道对代替。

于 2010-10-27T09:56:22.417 回答
3

与其这样做,不如使用依赖注入来删除直接使用std::cout. 在您的测试代码中,使用类std:ostringstream的模拟对象作为模拟对象,而不是真正的std::cout.

所以代替这个:

 void func() {
    ...
    std::cout << "message";
    ...
 }

 int main (int argc, char **argv) {
    ...
    func();
    ...
 }

拥有这个:

 void func(std::ostream &out) {
    ...
    out << "message";
    ...
 }

 int main(int argc, char **argv) {
    ...
    func(std::cout);
    ...
 }
于 2017-12-14T21:22:09.750 回答
1

将 Wgaffa 的建议(我喜欢)放到 Google 测试装置中,可能会这样写:

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

于 2019-10-14T03:07:05.803 回答
0

我们正在做你所指的事情。

首先我们创建了一些宏:

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

请参阅此答案以捕获 stdout 和 stderr: https : //stackoverflow.com/a/5419409/9796918 只需使用它们的 BeginCapture()、EndCapture() 代替我们的 redirect() 和 reset()。

在 AssertInfoMsgOutput 方法中:

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

现在在您的单元测试中,只需将您想要捕获 stdout/stderr 的调用包装起来:

    CAPTURE_STDOUT
    // Make your call to your code to test / capture here
    ASSERT_INFO( 1, "Foo bar" );
    RELEASE_STDOUT
于 2019-02-16T18:41:37.850 回答
0

根据 Wgaffa 的回答,我制作了这个辅助类,可以使用std::coutor构造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;

};
于 2019-07-23T15:47:45.193 回答