title: How to test for equality of complex object graphs?
body: <p>Say I have a unit test that wants to compare two complex for objects for equality. The objects contains many other deeply nested objects. All of the objects' classes have correctly defined <code>equals()</code> methods.</p>
  
  <p>This isn't difficult:</p>
  
  <pre><code>@Test
  public void objectEquality() {
      Object o1 = ...
      Object o2 = ...
  
      assertEquals(o1, o2);
  }
  </code></pre>
  
  <p>Trouble is, if the objects are not equal, all you get is a fail, with no indication of which part of the object graph didn't match. Debugging this can be painful and frustrating.</p>
  
  <p>My current approach is to make sure everything implements <code>toString()</code>, and then compare for equality like this:</p>
  
  <pre><code>    assertEquals(o1.toString(), o2.toString());
  </code></pre>
  
  <p>This makes it easier to track down test failures, since IDEs like Eclipse have a special visual comparator for displaying string differences in failed tests. Essentially, the object graphs are represented textually, so you can see where the difference is. As long as <code>toString()</code> is well written, it works great.</p>
  
  <p>It's all a bit clumsy, though. Sometimes you want to design toString() for other purposes, like logging, maybe you only want to render some of the objects fields rather than all of them, or maybe toString() isn't defined at all, and so on. </p>
  
  <p>I'm looking for ideas for a better way of comparing complex object graphs. Any thoughts?</p>