Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test function writing to stdout / std::cout

I am studying unit testing. From what I've seen, almost all unit tests use return value or an output parameter as the expected value in their test case.

What would be the expected value for a function that has no return value or output parameter?

Example:

void unit_test()
{
  cout << "Hello" << endl;
}

Sure, this function is very simple. So, this function does not seem to need to unit test. But this is just a sample. Do you think unit_test function has a side-effect? How would you test it?

like image 982
cardbt Avatar asked Nov 16 '10 03:11

cardbt


1 Answers

If you are writing a function that you know should be tested, then you should design it to be testable in your framework. Here, if your testing is done at a process level where you can verify the process output, then writing to std::cout is fine. Otherwise, you may want to make the output stream a parameter to the function, as in:

void unit_test(std::ostream& os = std::cout) 
{ 
  os << "Hello" << endl; 
} 

Then you can test it as in:

std::ostringstream oss;
unit_test(oss);
assert(oss && oss.str() == "Hello");

As this illustrates, making well-tested software requires a bit of give and take... testing requirements feed back into design.

EDIT: if you must test pre-existing functions without changing them, then consider:

#include <sstream>
#include <iostream>

void f()
{
    std::cout << "hello world\n";
}

int main()
{
    std::ostringstream oss;
    std::streambuf* p_cout_streambuf = std::cout.rdbuf();
    std::cout.rdbuf(oss.rdbuf());

    f();

    std::cout.rdbuf(p_cout_streambuf); // restore

    // test your oss content...
    assert(oss && oss.str() == "hello world\n";
    std::cout << oss.str();
}
like image 76
Tony Delroy Avatar answered Sep 20 '22 15:09

Tony Delroy