I am trying to find a good way to unit test my implementation of operator<< in C ++. I have a class that implements the operator, and a given instance with a certain state, I would like to check that the output is what I want.
This is my code (header file):
class Date { virtual int year() const { return 1970; }; virtual int month() const { return 1; }; virtual int day() const { return 1; }; friend std::ostream &operator<<(std::ostream &os, const Date &d); }; std::ostream &operator<<(std::ostream &os, const Date &d) { os << d.year() << "-" << d.month() << "-" << d.day(); return os; };
Now, in my unit test method, I could just do Date d; cout << d; Date d; cout << d; and check when I run the tests so that the result is correct. However, I would rather test this programmatically, so I donβt need to look at the test result more than at the final report (which, we hope, says β0 failed tests!β).
I'm new to C ++, so I have never used streams for anything other than input and output.
How to do it?
source share