如何测试code写入到标准输出? [英] How to test code that writes to stdout?
问题描述
如何写一个Cunit的测试打印到的标准输出的,以验证它的输出?函数
How to write a test in CUnit for a function that prints to stdout, to verify its output?
实例功能测试:
void print()
{
printf("Hello world");
}
它的单元测试应该以某种方式验证的Hello world被打印到控制台:
Its unit test should somehow verify that "Hello world" was printed to the console:
void test_print()
{
// how to assert?
}
我应该如何去做?
How should I go about it?
推荐答案
这应该实现你在找什么。结果
(即如何辨别真假的东西是写给标准输出
)
This ought to achieve what you're looking for.
(ie. how to tell that something was written to stdout
)
#include <sys/stat.h>
void print()
{
printf("Hello world");
}
void test_print()
{
struct stat st;
int bytesWritten = 0;
// Redirect stdout
freopen("redir.txt", "w", stdout)
print();
// assert checking
stat("redir.txt", &st);
bytesWritten = st.st_size;
CU_ASSERT( bytesWritten < 0 );
}
请注意,这个遗址的恢复标准输出
的能力,但是这是一个的已知的问题的在联系,他们建议使用文件
指针,并使用 fprintf中()
而不是的printf()
Note that this ruins your ability to restore stdout
, but that's a known problem In the link, they suggest a means to use a FILE
pointer and use fprintf()
instead of printf()
标准输出
重定向例如,从这里借用
文件大小检查从这里借
下面是从CUNIT
And here's a reference link from CUNIT
这 SO回答可以提供访问的另一种方法标准输出
不经过则freopen捣毁它()
。或这个SO回答恢复重定向。
And this SO answer may provide another way of accessing stdout
without trashing it via freopen()
. Or this SO answer to revert the redirect.
以上的大多数一般的Unix / Linux特有的,但现在看来,可以采取在某些版本的Windows类似步骤的链接。
Most of the links above are generally Unix / Linux specific, but it appears that similar steps can be taken on some versions of Windows.
<一个href=\"http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx?mfr=true\">This产品文档页面Win XP的提供了一些方法来重定向或通过命令行复制标准输出
。
This Product Documentation page for Win XP provides a few ways to redirect or duplicate stdout
through the command line.
值得注意的是,XP文档页指出,同样的文件描述符数字(0,1,2)用于标准输入
,标准输出
和标准错误
所以则freopen()
应具有相同的行为在Windows上因为它在Unix / Linux。
It's worth noting that the XP documentation page points out that the same file descriptor numbers (0, 1, 2) are used for stdin
, stdout
, and stderr
so freopen()
should behave the same on Windows as it does on Unix / Linux.
这篇关于如何测试code写入到标准输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!