2010-09-27 191 views
31

使用googletest框架时可以捕获stdout和stderr吗?如何使用googletest捕获stdout/stderr?

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

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

+4

从设计的角度来看,我建议修改的实施,使切换到日志文件是那么痛苦。例如,使用'ostream'接口会更容易。 – 2010-09-27 12:01:47

回答

24

在测试输出时,我已经使用此片段将cout调用重定向到stringstream。希望它可能引发一些想法。我以前从未使用过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

避免这样做总是一个好的设计理念。如果你真的想这样做了以下工作:

#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); 
} 

要使用标准错误而不是标准输出改变的第二个参数DUP2为2。对于没有通过,你可以使用管道对,而不是一个文件去捕捉。

+4

当然这也是不可移植到没有dup2的系统... – Flexo 2010-10-27 09:57:43

49

Googletest此提供各种功能:

testing::internal::CaptureStdout(); 
std::cout << "My test" 
std::string output = testing::internal::GetCapturedStdout(); 
+0

可能是最简单的可能解决方案 – 2015-10-26 01:54:31

+0

这只适用于'stdout',而不是'stderr'?有死亡测试可以捕获“stderr”,但在很多情况下,您可能没有测试过程终止。 – meowsqueak 2015-11-25 01:53:41

+1

testing :: internal :: CaptureStderr()也存在。这里使用例如:https://googletest.googlecode.com/svn/trunk/test/gtest-death-test_test.cc – Heinzi 2015-11-25 14:37:50

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); 
    ... 
}