title: Unit testing operator<< in C++
body: <p>I'm trying to figure out a nice way to unit test my implementation of the <code>operator&lt;&lt;</code> 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.</p>
  
  <p>This is my code (the header file):</p>
  
  <pre><code>class Date {
      virtual int year() const { return 1970; };
      virtual int month() const { return 1; };
      virtual int day() const { return 1; };
      friend  std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, const Date &amp;d);
  };
  
  std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, const Date &amp;d) {
      os &lt;&lt; d.year() &lt;&lt; "-" &lt;&lt; d.month() &lt;&lt; "-" &lt;&lt; d.day();
      return os;
  };
  </code></pre>
  
  <p>Now, in my unit test method, I could just do <code>Date d; cout &lt;&lt; d;</code> 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!").</p>
  
  <p>I'm fairly new with C++, so I've never really used streams for anything but input and output.</p>
  
  <p>How do I accomplish this?</p>