How to unit test function writing to stdout / std::cout
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();
}