使用googletest框架时是否可以捕获stdout和stderr?
例如,我想调用一个将错误写入控制台(stderr)的函数。 现在,在测试中调用函数时,我想断言那里没有输出。
或者,也许我想测试错误行为,并希望断言当我(故意)产生错误时会打印某个字符串。
答案 0 :(得分:65)
Googletest为此提供了以下功能:
testing::internal::CaptureStdout();
std::cout << "My test";
std::string output = testing::internal::GetCapturedStdout();
答案 1 :(得分:30)
我之前使用过此片段,在测试输出时将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);
在重定向回原始输出之前,请使用google测试检查缓冲区中的输出。
答案 2 :(得分:2)
避免必须这样做总是一个好的设计理念。如果你真的想这样做,可以做以下工作:
#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.对于不通过文件进行捕获,您可以使用管道对。
答案 3 :(得分:1)
使用依赖注入来删除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);
...
}
答案 4 :(得分: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
答案 5 :(得分:0)
根据Wgaffa的回答,我制作了可以用std::cout
或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;
};
答案 6 :(得分:0)
将Wgaffa的建议(我喜欢)放入Google Test固定装置,可能会这样写:
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