c++ - How to unit test function writing to stdout / std::cout -
these days, studying unit test. unit test use return value or reference value expected value in test case. if has not return value , reference value in function. expected value?
exsample-
void unit_test() { cout << "hello" << endl; }
sure, unit_test
function simple. so, function not seem need unit test. but, sample. think unit_test
function has side-effect.
thank you, , please understand fool english.
if writing function know should tested, should design testable in framework. here, if testing done @ process level can verify process output, writing std::cout fine. otherwise, may want make output stream parameter function, in:
void unit_test(std::ostream& os = std::cout) { os << "hello" << endl; }
then can test in:
std::ostringstream oss; unit_test(oss); assert(oss && oss.str() == "hello");
as illustrates, making well-tested software requires bit of give , take... testing requirements feed design.
edit: if must test pre-existing functions without changing them, 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 oss content... assert(oss && oss.str() == "hello world\n"; std::cout << oss.str(); }
Comments
Post a Comment