-
Notifications
You must be signed in to change notification settings - Fork 44
Make Builders Invisible to Production Code
Michael Karneim edited this page Dec 21, 2017
·
10 revisions
I often hear and sometimes read that PojoBuilder is not that great for generating test data because it seemingly pollutes production code.
The following reasons are given:
- PB requires modification of production code because of the
@GeneratePojoBuilder
annotation, which has to be placed on the production classes. - PB stores the generated builder classes into the production class tree, hence they are accessibly not only by test code but also by production code.
While it can be discussed whether it really is that bad that test code has any influence on production code, those specific reasons are not compelling.
- Actually the
@GeneratePojoBuilder
annotation is only visible at compile-time since its retention policy is CLASS. During runtime, e.g. by using reflection likemyPojoClass.getAnnotations()
, it's completely invisible. More particularly, the PB library is not required to be part of your runtime classpath at all. - To ensure that the generated builders are part of the test scope only, you can refrain from annotating the pojo class itself. Instead you might want to create a factory class as part of your test class tree and provide an annotated factory method for each of your pojos, like in the following example:
public class PojoFactory {
@GeneratePojoBuilder
public static Order newOrder() {
return new Order();
}
@GeneratePojoBuilder
public static Customer newCustomer(String name, String address) {
// this is an example with mandatory constructor parameters
return new Customer(name, address);
}
}
While maintaining such a class is a small overhead, this ensures that the generated builders become part of your test class tree only and therefore are not accessible by production code by any means.