In addition to Sergey
's great answer above, you may choose to have std::cout
as a default parameter.
So, if you have a code:
// Only need console output
using std::cout;
...
void toBeTested()
{
cout << "This is the correct output.";
}
And it is used (or may be frequently used in the future) in many places:
int main()
{
...
toBeTested();
...
toBeTested();
...
// And so on...
return 0;
}
In order to avoid breaking a lot of code and maintaining a simple interface,
you can convert the above function to:
using std::cout;
...
void toBeTested(std::ostream& cout = std::cout)
{
cout << "This is the correct output.";
}
And your main
does not need to be touched.
Note that cout
of the function now overshadows cout
of the global scope. Therefore, this cout
can be any output stream, and does not interfere with the global cout
.
And now you can test this as above!
#include <sstream>
#include <cassert>
...
void testMyFunctionDisplay()
{
// Arrange
std::ostringstream output_buffer;
// Act
toBeTested(output_buffer);
// Assert
assert(output_buffer.str() == "This is the correct output.");
}
However. it is not necessary to make every function in this way.
It is useful if we want to redirect that function's output to other output streams:
- Stringstreams: If you want to use the output somewhere, perhaps for testing the module, or for other purposes in the program.
- Files: If you want to maintain the output even after the program termination.
std::cout
directly and write tostd::ostream&
references. Then the testing framework can pass instd::ostringstream
objects while the application passes instd::cout
. – Zelma