I’m trying to figure out a nice way to unit test my implementation of the operator<< in C++. I have a class which implements the operator, and given an instance with a specific state, I’d like to check that the output is what I want it to be.
This is my code (the 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; and verify when I run the tests that the output is correct. However, I’d much rather programmatically verify this, so I don’t have to look at the test output more than at the final report (which hopefully says “0 failed tests!”).
I’m fairly new with C++, so I’ve never really used streams for anything but input and output.
How do I accomplish this?
You can use a
std::stringstreamto hold the result, and then callstr()on it to get a string:Note: I spent quite a while looking for a decent unit testing framework in C++ and the best I found at the time was googletest — in case you haven’t picked a framework yet.