C ++单元测试检查输出是否正确 [英] c++ unit testing check output is correct

查看:143
本文介绍了C ++单元测试检查输出是否正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想编写自己的test.cpp来检查另一个.cpp文件是否以我希望的输出方式输出,是否有必要在不显式打印的情况下进行操作?

If I want to write my own test.cpp that checks if another .cpp file is outputting the way I want it to output, is there anyway to do it without explicitly printing it?

换句话说,有诸如

assert(output_of_file_being_tested, "this is the correct output");

其中output_of_file_being_tested是应该被"cout"的东西.

where output_of_file_being_tested is something that's supposed to be "cout"ed.

推荐答案

解决方案不是对输出流进行硬编码.以某种方式将对std::ostream的引用传递给您的代码,然后使用std::stringstream在测试环境中收集输出.

The solution is not to hard-code the output stream. Pass a reference to std::ostream to your code somehow, and use std::stringstream to collect the output in test environment.

例如,这是您的另一个.cpp"文件的内容:

For example, this is the content of your "another .cpp" file:

void toBeTested(std::ostream& output) {
        output << "this is the correct output";
}

因此,在生产/发布代码中,您可以将std::cout传递给函数:

So in your production/release code you may pass std::cout to the function:

void productionCode() {
        toBeTested(std::cout);
}

在测试环境中,您可以将输出收集到字符串流中并检查其正确性:

while in the test environment you may collect the output to a sting stream and check it for correctness:

// test.cpp
#include <sstream>
#include <cassert>

void test() {
        std::stringstream ss;
        toBeTested(ss);
        assert(ss.str() == "this is the correct output");
}

这篇关于C ++单元测试检查输出是否正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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