The TestDataBuilder pattern is used in unit testing to create collaborators. Its advantages versus using constructors:
- Changes to constructors are localized.
- Test code becomes clearer, because you don't have to specify all the required parameters to the constructor.
A disadvantage is that the usage is somewhat lengthy which decreases readability:
var service = serviceBuilder.WithRepo(
repoBuilder.WithEntities(
new [] { entityBuilder.WithName("name") }).Build())
.WithMailSender(mailSenderBuilder.Build())
.Build();
- The word "With" is typically repeated many times.
- Same for the call to
Build()
. - Same for the word
Builder
.
Although all of them can be mitigated, I guess the solutions themselves have drawbacks. For instance, we could rename serviceBuilder
to service
, but this could give the wrong impression about the type of the variable. We could implement an implicit conversion from a builder class to the object it builds, but it is more code in the builder in addition to already abundant With*
methods.
Is there an alternative to TestDataBuilder that doesn't have these drawbacks?