title: Testing builder pattern in Java
body: <p>We use the builder pattern extensively in our code base, with built objects all having a <code>toBuilder()</code> method. I want to write a unit test that ensures that no fields have been forgotten in the <code>toBuilder()</code> methods, i.e., for any buildable object, I want to a test roughly like this</p>
  
  <pre><code>MyClass obj = getTestObjectWithRandomData();
  assertEquals(obj, obj.toBuilder().build());
  </code></pre>
  
  <p>Now, I can fairly easy write a basic version of <code>getTestObjectWithRandomData()</code> that uses reflection to assign a bunch of values to the fields of any object. However, the snag is that <code>build()</code> often contains tons of validation checks that will throw exceptions if, for example, a certain integer isn't within a sane range. Writing a generalized version of <code>getTestObjectWithRandomData()</code> that conforms all those class-specific validation checks would be impossible.</p>
  
  <p>So, how can I do what I want to do? I'm tempted to segregate the construction and validation code into different methods so that the test doesn't trip on the validation, but then that means that people have to remember to call <code>validate()</code> or whatever on objects after they create them. Not good.</p>
  
  <p>Any other ideas?</p>