c++ unit testing check output is correct

assert, c++, cout, output, unit-testing

Solution

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.

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

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

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

Problem

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? In other words, is there anything such as ``` assert(output_of_file_being_tested, "this is the correct output"); ``` where output_of_file_being_tested is something that's supposed to be "cout"ed.

Original source

Related problems