5

Is there a framework or library available that, when given a JavaBean, will "put it through its paces," i.e., test all the getters and setters, validate that a property matches the getters and setters, etc.?

2
  • you could roll your own via reflection
    – hvgotcodes
    Jul 20, 2010 at 22:42
  • 1
    If there are problems with your getters and setters and somehow your other (real) tests don't expose them (i.e. fail) then there are issues with the rest of your test suite
    – matt b
    Jul 21, 2010 at 0:21

7 Answers 7

8

Personally, I don't think that's the hardest part of testing. It'd be possible to do via reflection, but that's not what makes testing worthwhile.

The hard part is figuring out all the possible inputs, for "happy path" and erroneous situations, making sure that exceptions are thrown when they should be, etc.

Your Java Bean should be implementing equals and hashCode. I'd worry more about tests to check the equals contract: null equals, reflexive, symmetric, transitive, and not equals. Those aren't trivial.

Getters and setters are the least of your problems. When people talk about code coverage standards of 70% or better they often say that getters and setters can be left out.

2
  • Agreed that it's not the hardest part; just tedious. I worked for an organization that wrote a bean testing framework just to get code coverage numbers up. Jul 21, 2010 at 20:25
  • 2
    I think that's a false measure. High coverage does not mean good tests. Something like CRAP4J can be a better indicator.
    – duffymo
    Jul 21, 2010 at 21:14
7

While I agree that there are bigger problems to solve, there are cases for testing Java bean methods. Large teams teams working on large codebases can run into problems. I've seen several cases of copy/paste error leading to getters or setters working on the wrong property. Forgetfulness can lead to hashCode and equals methods becoming inconsistent. Finding bugs in this simple code can be very frustrating.

Bean Matchers is a library that can help in this regard. It provides a series of Hamcrest matchers for reflectively testing Java beans. For example:

@Test
public void testBean() {
    assertThat(MyBean.class, allOf(
            hasValidBeanConstructor(),
            hasValidGettersAndSetters(),
            hasValidBeanHashCode(),
            hasValidBeanEquals(),
            hasValidBeanToString()
    ));
}
1
2

Take a look at Reflection Test Utilities:

http://code.google.com/p/rtu/

Although if you're testing generated methods (based on fields in a class) it may not be worth it.

1
1

If you're not looking like something more fancy like http://commons.apache.org/validator/ I would recommend to write your own. Personally I don't like pure data holding objects without any behaviour - it's not very good design. So if I'm not forced to work with such objects (by working with j2ee f. e.), I try to get rid of them.

1

You could try http://oval.sourceforge.net/ Oval it allows you to use annotations on your beans and then execute a validate method. It's not fully JSR303 compliant. If you want to use something fully compliant you should check out the Hibernate Validator.

Like the post above states definitely check out apache commons validator.

1

Answering this in 2021 because sadly, this problem still exists.

Beans add up to the code base and have a very negative impact if your DevOps pipelines are imposing coverage restrictions on repos. There are two ways to overcome it.

  1. Exclude the beans ( which I would say should not be done).

  2. Write test cases for beans ( which is the most pathetic thing that we as a developer can do to waste our time :( ).

And in most cases, you will end up writing test cases for beans.

I have written this simple Utility/test case that uses reflection and can allow you to increase the Junit code coverage and save your time.

Bean under test: City

package com.test.beans;

import java.util.List;

/**
 * @author ameena
 *
 */
public class City {
    private int postOffices;
    private int jurdictaionAreas;
    private double areaInSqMeter;
    private long population;
    private List<City> neighbourCities;
    private boolean metro;

    public int getJurdictaionAreas() {
        return jurdictaionAreas;
    }

    public void setJurdictaionAreas(int jurdictaionAreas) {
        this.jurdictaionAreas = jurdictaionAreas;
    }

    public double getAreaInSqMeter() {
        return areaInSqMeter;
    }

    public void setAreaInSqMeter(double areaInSqMeter) {
        this.areaInSqMeter = areaInSqMeter;
    }

    public long getPopulation() {
        return population;
    }

    public void setPopulation(long population) {
        this.population = population;
    }

    public int getPostOffices() {
        return postOffices;
    }

    public void setPostOffices(int postOffices) {
        this.postOffices = postOffices;
    }

    public List<City> getNeighbourCities() {
        return neighbourCities;
    }

    public void setNeighbourCities(List<City> neighbourCities) {
        this.neighbourCities = neighbourCities;
    }

    public boolean isMetro() {
        return metro;
    }

    public void setMetro(boolean metro) {
        this.metro = metro;
    }
}

The class to automate the bean testing


package com.test.beans;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.junit.jupiter.api.Test;

/**
 * @author ameena
 *
 */
class BeanTest {

    public void invokeSetter(Object obj, String propertyName, Object variableValue)
    {
        PropertyDescriptor propDescriptor;
        try {
            propDescriptor = new PropertyDescriptor(propertyName, obj.getClass());
            Method setter = propDescriptor.getWriteMethod();
            try {
                setter.invoke(obj,variableValue);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                e.printStackTrace();
                fail(e.getMessage());
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
            fail(e.getMessage());
        }

    }

    public Object invokeGetter(Object obj, String variableName)
    {
        Object returnValue = null;
        try {
            PropertyDescriptor pd = new PropertyDescriptor(variableName, obj.getClass());
            Method getter = pd.getReadMethod();
            returnValue = getter.invoke(obj);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | IntrospectionException e) {
            e.printStackTrace();
            fail(e.getMessage());
        }
        return returnValue;
    }


    private <T extends Object> void validateGettersSetters(List<T> objects) {
        for (T t : objects) {
            Class<?> aClass = t.getClass();
            for (java.lang.reflect.Field field : aClass.getDeclaredFields()) {
                System.out.println(field);
                Class<?> c = field.getType();
                if (c == String.class) {
                    invokeSetter(t, field.getName(), "dummy");
                    assertEquals("dummy", (invokeGetter(t, field.getName())));
                } else if (c == Integer.class || c == int.class) {
                    invokeSetter(t, field.getName(), 1);
                    assertEquals(1, (invokeGetter(t, field.getName())));
                }else if (c == Double.class || c == double.class) {
                    invokeSetter(t, field.getName(), 1d);
                    assertEquals(1d, (invokeGetter(t, field.getName())));
                }else if (c == Long.class || c == long.class) {
                    invokeSetter(t, field.getName(), 1l);
                    assertEquals(1l, (invokeGetter(t, field.getName())));
                }else if (c == Boolean.class || c == boolean.class) {
                    invokeSetter(t, field.getName(), true);
                    assertEquals(true, (invokeGetter(t, field.getName())));
                }else if (c == List.class){
                    //Now based on your bean and filed name
                    switch(field.getName()) {
                    case "neighbourCities" :
                        invokeSetter(t, field.getName(), new ArrayList<City>());
                        assertNotNull(invokeGetter(t, field.getName()));
                        break;
                }
            }
        }
    }
    }

    @Test
    void testBean() {
        List<Object> objects = new ArrayList<>();
        objects.add(new City());
        validateGettersSetters(objects);

    }

}

Nothing fancy, but it saved me for writing test cases for 23 beans :)

Regards Amit Meena

0

I guess this library is the answer to your question: http://outsidemybox.github.com/testUtils/

it tests all the bean's initial values, the setters, the getters, hashCode(), equals() and toString(). All you have to do is define a map of default and non default property/value.

It can also test objects that are beans with additional non default constructors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.