Rapid device testing << in C ++

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?

+4
source share
1 answer

You can use std::stringstream to save the result, and then call str() in to get the string:

 #include "Date.h" #include <iostream> #include <sstream> int main() { Date d; std::stringstream out; out << d; if(out.str() == "1970-1-1") { std::cout << "Success"; } else { std::cout << "Fail"; } } 

Note. I spent a lot of time looking for a decent unit testing system in C ++, and the best I found at that time was googletest - in case you hadn't chosen a framework yet.

+17
source

Source: https://habr.com/ru/post/1441898/


All Articles