Google Test c++:有没有一种方法可以在测试中读取当前控制台的输出?
Google Test C++: Is there a way to read the current console output in a test?
让我们假设我有一个要测试的类,它有以下方法:
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());
}
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- C++ gmock - 我们如何在单元测试 cpp 文件中读取/获取 cpp 文件函数的参数值
- 我的 Visual c++ 托管单元测试项目未读取输入文件
- 从文件中逐块读取,然后逐行拆分测试
- 为什么在我的测试程序中,从字符缓冲区读取一个int时,"std::copy"5x(!)比"
- 从字符串流读取和写入自定义对象时测试失败
- 如何从 stdin(对于 C++ 中给定数量的测试用例)读取数据
- 在测试用例中读取qdebug
- Google Test c++:有没有一种方法可以在测试中读取当前控制台的输出?