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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With