Google Test c++:有没有一种方法可以在测试中读取当前控制台的输出?

Google Test C++: Is there a way to read the current console output in a test?

本文关键字:读取 测试 输出 控制台 有没有 c++ Test 方法 一种 Google      更新时间:2023-10-16

让我们假设我有一个要测试的类,它有以下方法:

void
MyClass::sayHello()
{
   std::cout << "Hello";
}

现在,在我的google测试中,我想验证这个输出是否已经完成。在下面的伪代码中使用的lastConsoleOutput等效是什么?

// Tests if sayHello() outputs Hello
TEST(MyClassTest, sayHello)
{
  EXPECT_EQ(lastConsoleOutput,"Hello");
}

感谢您的任何反馈!

在这种情况下,我将避免重定向或测试stdout或stderr中的值,因为对这些流的访问不是线程安全的,输出缓冲区可能不会像预期的那样被追加和刷新。

从测试的角度来看,我建议将方法重构为无状态,并将状态(也称为std::cout)保留在其他地方。在您的示例中,您开始测试外部API的行为,而不是对象中的实际修改。

class MyClass {
    std::sstream state;
public:
    void print(){ std::cout << state.str(); } // no need to test this method, only external API
    void changeState() {
        state << "Hello" << std::endl; // this should be tested 
    }
}
在您的测试代码中,您现在可以很容易地使用 执行测试
// Tests if sayHello() outputs Hello
TEST(MyClassTest, sayHello)
{
  myClass.changeState();
  EXPECT_STREQ(myClass.state.str().c_str(),"Hello");
}

我避免使用像您的sayHello()方法那样的代码。我会把它重构成这样:

void MyClass::sayHello(std::ostream& out) {
    out << "Hello";
}

那么测试方法就像这样:

TEST(MyClassTest, sayHello) {
  MyClass c;
  std::stringstream strm;
  c.sayHello(strm);
  EXPECT_STREQ("Hello", strm.str.c_str());
}