Generally standard getters and setters can be generated by your IDE but testing them is a manual work - it takes some time and seems to be boring. So if the code was generated, why can't we automate the testing?
openpojo doesn't generate the unit test but it allows to test your POJO with a very small effort.
Let's take a look at an example. We have a Person class which is a POJO with generated getters and setters.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package pl.mjedynak.openpojo; | |
public class Person { | |
private String name; | |
private int age; | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
public int getAge() { | |
return age; | |
} | |
public void setAge(int age) { | |
this.age = age; | |
} | |
@Override | |
public boolean equals(Object o) { | |
if (this == o) return true; | |
if (!(o instanceof Person)) return false; | |
Person person = (Person) o; | |
if (age != person.age) return false; | |
if (name != null ? !name.equals(person.name) : person.name != null) return false; | |
return true; | |
} | |
@Override | |
public int hashCode() { | |
int result = name != null ? name.hashCode() : 0; | |
result = 31 * result + age; | |
return result; | |
} | |
} |
To test it we need to create just one class:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PojoTest { | |
private static final String POJO_PACKAGE = "pl.mjedynak.openpojo"; | |
private List<PojoClass> pojoClasses; | |
private PojoValidator pojoValidator; | |
@Before | |
public void setup() { | |
pojoClasses = PojoClassFactory.getPojoClasses(POJO_PACKAGE, new FilterPackageInfo()); | |
pojoValidator = new PojoValidator(); | |
pojoValidator.addRule(new GetterMustExistRule()); | |
pojoValidator.addRule(new SetterMustExistRule()); | |
pojoValidator.addTester(new SetterTester()); | |
pojoValidator.addTester(new GetterTester()); | |
} | |
@Test | |
public void testPojoStructureAndBehavior() { | |
for (PojoClass pojoClass : pojoClasses) { | |
pojoValidator.runValidation(pojoClass); | |
} | |
} | |
} |
Running the class with any coverage tool will show us that the get and set methods are executed.
There are more rules that we can apply (like checking if there are no public fields, no primitive values etc.). We can write our own rules as well.