将cout和stdout都重定向到C ++中的字符串以进行单元测试 [英] Redirect both cout and stdout to a string in C++ for Unit Testing

查看:2294
本文介绍了将cout和stdout都重定向到C ++中的字符串以进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力在单元测试下获得一些遗留代码,有时,感知现有程序行为的唯一方法是从控制台输出。



我看到很多在线示例如何将stdout重定向到C ++中的另一个文件,但是有一种方法,我可以将它重定向到内存流,所以我的测试不必依赖磁盘?



我想获得任何遗留代码发送到stdout到std ::字符串,所以我可以很容易地在输出.find。



编辑



旧代码太糟糕了,因此用户混合使用 cout< .. printf 。这是我到目前为止:

  void TestSuite :: setUp(void)
{
oldStdoutBuf = std :: cout.rdbuf();
std :: cout.rdbuf(consoleOutput.rdbuf());
}
void TestSuite :: tearDown(void)
{
std :: cout.rdbuf(oldStdoutBuf);
}

问题是这样做使用printf。我想要的东西,得到两者。任何想法?

解决方案

std :: stringstream 可能是您要查找的内容。



UPDATE

好​​吧,这是一个黑客,但也许你可以这样做,以获取printf输出:

  char huge_string_buf [MASSIVE_SIZE]; 
freopen(NUL,a,stdout);
setbuf(stdout,huge_string_buffer);注意,你应该使用/ dev / null替换linux,而不是NUL。这将迅速开始填满huge_string_buffer。如果你想要能够在缓冲区满后继续重定向输出,你必须调用fflush(),否则会抛出一个错误。请参见 std :: setbuf 了解更多信息。


I'm working on getting some legacy code under unit tests and sometimes the only way to sense an existing program behavior is from the console output.

I see lots of examples online for how to redirect stdout to another file in C++, but is there a way I can redirect it to an in-memory stream so my tests don't have to rely on the disk?

I'd like to get anything that the legacy code sends to stdout into a std::string so I can easily .find on the output.

Edit

The legacy code is so bad that it users a mixture of cout << .. and printf. Here is what I have so far:

void TestSuite::setUp(void)
{
    oldStdoutBuf = std::cout.rdbuf();
    std::cout.rdbuf(consoleOutput.rdbuf());
}
void TestSuite::tearDown(void)
{
    std::cout.rdbuf(oldStdoutBuf);
}

The problem is that this does not capture output using printf. I would like something that gets both. Any ideas?

解决方案

std::stringstream may be what you're looking for.

UPDATE
Alright, this is a bit of hack, but maybe you could do this to grab the printf output:

char huge_string_buf[MASSIVE_SIZE];
freopen("NUL", "a", stdout);
setbuf(stdout, huge_string_buffer);

Note you should use "/dev/null" for linux instead of "NUL". That will rapidly start to fill up huge_string_buffer. If you want to be able to continue redirecting output after the buffer is full you'll have to call fflush(), otherwise it will throw an error. See std::setbuf for more info.

这篇关于将cout和stdout都重定向到C ++中的字符串以进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆