OpenPojo – Setter and Getter Unit-Test

Writing an entity can be a mindless task. Typing down the attributes of the entities, generate / write getter and setter. No fancy or special things on this.
Additionally to all this we have to test our implementations. Even though we have just implemented setter and getter which don´t contain business logic.
But we don´t want to write a test method for every setter and getter pair. Doing this, we would waste a lot of precious time we need to develop our business logic.


Let us create a simple entity, for example a User.

package com.javadevcorner.entity;

import java.time.LocalDate;

 * @author
public class User {

    private int id; 
    private String name;
    private LocalDate birthday; 

    //getter and setter

Add OpenPojo via Maven

Just add this dependency to your pom.xml


Maybe you need to clean install your project to use the new dependency.

Implement our Unit-Test

Create a JUnit-Test class and implement the test as follows:

package com.javadevcorner.entity;

import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.impl.PojoClassFactory;
import com.openpojo.validation.Validator;
import com.openpojo.validation.ValidatorBuilder;
import com.openpojo.validation.rule.impl.GetterMustExistRule;
import com.openpojo.validation.rule.impl.SetterMustExistRule;
import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
import org.junit.Test;
 * @author
public class UserTest {

    public void testGetterSetter() {
        PojoClass pojoclass = PojoClassFactory.getPojoClass(User.class);
        Validator validator = ValidatorBuilder
                .with(new SetterMustExistRule())
                .with(new GetterMustExistRule())
                .with(new SetterTester())
                .with(new GetterTester())


We declare an instance of PojoClass via the PojoFactory with our User class.

After that, we instanciate the OpenPojo validator and tell him which methods (rules) he has to test. For example you can tell him, to only test the getter methods.

If you now start your Unit test, it will result in a passed (green) test. The test would fail if you delete one getter or setter in our entity. Feel free to try it.

Of course this little setter and getter Test will also work if your entity is using project lombok.

So thanks for reading and have fun using OpenPojo.

Feel free to share

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.