Why Test Data Builders Are Good
This morning at Code Camp, Shaun Abram (http://www.shaunabram.com/) asked me about my "Building Better Tests in Java" presentation where I talked about using Test Data Builders instead of Factory classes (what we at Guidewire call DataGen classes). He said that he liked Builders, but wasn’t sure what the compelling benefits were. I’m glad he asked because besides giving me an idea for a blog entry, it’ll make me go back and make it more clear.
If you were at the presentation, here’s the reasons that I had hoped to get across:
- Prevent the combinatorial explosion of variations on methods to create an entity. In one example, we had 12 different variations to create a Policy. Yikes.
- Tests become much more readable. For example, would you rather read:
Activity myActivity = DataGen.activity( true, true, false, true, true, Status.NEW, Priority.MEDIUM, false );or, with a test data builder:
Activity myActivity = new ActivityBuilder()
.autoGenerated()
.notEscalated()
.ownedExternally()
.mandatory()
.recurring()
.statusNew()
.priorityMedium()
.shared()
.create();
If you said the first one, you’re far too familiar with our Activity entity and probably work at Guidewire.
Shaun also mentioned a problem where someone comes along and changes one of the defaults (i.e., the value of a property that wasn’t specified) in a factory method to fit the test they’re writing, only to break a bunch of other tests that relied on different defaults. They probably did that because they didn’t want to create yet another factory method that took the property as a parameter so they could choose a different value.
Chained Methods and the Fluent Interface
Also, Jeff Brown (http://blog.bits-in-motion.com/) at the BBQ last night mentioned that he was surprised I didn’t use the phrase "fluent interface" and he’s right! OMG! There goes my credibility. Seems like a need to rework my Builders presentation, but I think I knew that.

