开发者

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 ret开发者_JAVA技巧urn 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?


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


Unit testing a function that returns void usually involves sending it inputs and catching any exceptions the function may throw when passed bad data. Your function doesn't take any inputs, so unit testing it seems unnecessary unless you want to test extreme conditions like running out of memory when you call the function.


In general, you don't unit test procedures (i.e. pieces of code like the one you put that doesn't take any inputs and doesn't return any values). For starters, try testing something that is a function (takes some parameters and returns some values).

That is, you test side effects - the only side effect of the function you provided is the characters being output to the console, something that is probably rarely tested.

Take a look at this primer:

  • http://code.google.com/p/googletest/wiki/Primer

or this one:

  • http://cunit.sourceforge.net/doc/writing_tests.html
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜