[ACCEPTED]-junit test method for getters & setters-getter-setter

Accepted answer
Score: 24

The philosophy of Test Driven Development 11 says "test everything which can possibly 10 break". That is, focus your efforts on the 9 useful tests, instead of writing tests for 8 just the sake of it.

Getters and setters 7 are almost always trivial code, which is 6 not worth testing by themselves.

I know this 5 is not a straight answer to your plea, but 4 I thought it may still help to point this 3 out ;-) So why do you actually need to write 2 tests for all those getters and setters 1 in the first place?

Score: 11

If you have 100 fields in a class (with 7 corresponding setters/getters) I suspect 6 your object model is not decomposed correctly. 100+ fields 5 sounds like an extraordinary number of fields 4 for an object, and I would guess that it 3 has several responsibilities that can be 2 split across a number of more specialised 1 objects.

Score: 5

You could perhaps use Apache Commons 'beanutils' to 12 help automate this:

http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/PropertyUtils.html#getSimpleProperty%28java.lang.Object,java.lang.String%29

For instance there is 11 a method describe(Object bean) which will return a map of all 10 the readable attributes (ie, getters).

Then 9 iterate that map and call:

setSimpleProperty(Object bean, String name, Object value)

and

public static Object getSimpleProperty(Object bean, String name)

And although 8 I agree with the other poster than getters/setters 7 are pretty trivial - I think it is still 6 worth testing them - to eliminate typos, test 5 property change listeners etc.

For example, this 4 will dynamically extract the getters of 3 a bean:

import java.io.Serializable;
import java.util.Set;
import org.apache.commons.beanutils.PropertyUtils;

public class MyTestBean implements Serializable {
    private int a;
    private int b;
    private int c;
    private String x;
    private String y;
    private String z;

    public static void main(String[] args) throws Exception {
    MyTestBean bean=new MyTestBean();
    Set prop=PropertyUtils.describe(bean).keySet();
    for (Object o : prop) {
        System.out.println((String)o);
    }
    }

    public int getA() {
        return a;
    }
    public void setA(int a) {
        this.a = a;
    }
    public int getB() {
        return b;
    }
    public void setB(int b) {
        this.b = b;
    }
    public int getC() {
        return c;
    }
    public void setC(int c) {
        this.c = c;
    }
    public String getX() {
        return x;
    }
    public void setX(String x) {
        this.x = x;
    }
    public String getY() {
        return y;
    }
    public void setY(String y) {
        this.y = y;
    }
    public String getZ() {
        return z;
    }
    public void setZ(String z) {
        this.z = z;
    }}

You will need to download both BeanUtils 2 and CommonsLogging and both libraries' JARs 1 to your project to run this code.

Score: 3

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

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

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

Score: 0

Answering this in 2021 because this problem 17 still persists.

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

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

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

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

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

Bean 4 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 3 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 2 me for writing test cases for 23 beans :)

Regards Amit 1 Meena

More Related questions