Test data generation is always a hot topic when it comes to automated software
testing. One of my first assignments at
4teamwork was to help with the testing. In
the process I was browsing through the test suites of some big projects they are
working on and noticed a lot of similar code related to data creation:
This is very basic object creation code and I’m sure many Plone developers have
written a fair amount of it. While this gets the job done, there is a lot of
noise, that we don’t need to have in every test.
I decided to use a basic implementation of the
Builder Pattern to hide the
noise in specific Builder classes and make our tests shorter and more
expressive at the same time:
Already a big step forward! We have only defined two Builder classes, and we
already notice some duplication among them. Defining a base class gives us a place
to store the shared behavior:
Finally we hide the different Builder implementations and their instantiation
behind a function. This allows us to change the Builders without touching all
the tests that use them:
1234567
defBuilder(name):ifname=="dossier":returnDossierBuilder()elifname=="document":returnDocumentBuilder()else:raiseValueError("No Builder for %s"%name)
And the final code inside the test-cases looks like: