Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ unit testing check output is correct

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.

like image 872
bananamuffin Avatar asked Oct 28 '16 03:10

bananamuffin


People also ask

Does C have unit testing?

A Unit Testing Framework for CCUnit is a lightweight system for writing, administering, and running unit tests in C. It provides C programmers a basic testing functionality with a flexible variety of user interfaces.

How does unit testing work in C?

Unit testing is a method of testing software where individual software components are isolated and tested for correctness. Ideally, these unit tests are able to cover most if not all of the code paths, argument bounds, and failure cases of the software under test.


1 Answers

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");
}
like image 126
Sergey Avatar answered Sep 20 '22 14:09

Sergey