C ++ unit test validation bug fixed

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

In other words, is there anything like

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

where output_of_file_being_tested is what the "cout" ed should be.

+4
source share
1 answer

The solution should not hard code the output stream. Pass the link to std::ostreamyour code somehow and use it std::stringstreamto collect the result in a test environment.

For example, this is the contents of your “other .cpp” file:

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

, / std::cout :

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

sting :

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

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

Source: https://habr.com/ru/post/1659135/


All Articles