且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++单元测试检查输出是否正确

更新时间:2023-11-29 15:25:58

解决方案不是对输出流进行硬编码.以某种方式将对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");
}