Junit Test of Setters and Getters of Instance Variables

The main principle of unit testing is that you test a simple unit of code; that is, each method should be tested on its own merits.

This means we can’t use the get method in our set test, and vice versa – you’re not testing the individual unit of code that is the single method.

Given that…

Let’s say we have a PlainOldJavaObject with a field value that we want (for some reason) to test the validity of setters and getters for. The only appropriate way to do this is through the use of reflection.

Here’s my class declaration, which is pretty skinny:

public class PlainOldJavaObject {

    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

I now set up my test class to make use of reflection; specifically using the Field class:

public class PlainOldJavaObjectTest {

    @Test
    public void testSetter_setsProperly() throws NoSuchFieldException, IllegalAccessException {
        //given
        final PlainOldJavaObject pojo = new PlainOldJavaObject();

        //when
        pojo.setValue("foo");

        //then
        final Field field = pojo.getClass().getDeclaredField("value");
        field.setAccessible(true);
        assertEquals("Fields didn't match", field.get(pojo), "foo");
    }

    @Test
    public void testGetter_getsValue() throws NoSuchFieldException, IllegalAccessException {
        //given
        final PlainOldJavaObject pojo = new PlainOldJavaObject();
        final Field field = pojo.getClass().getDeclaredField("value");
        field.setAccessible(true);
        field.set(pojo, "magic_values");

        //when
        final String result = pojo.getValue();

        //then
        assertEquals("field wasn't retrieved properly", result, "magic_values");
    }

}

In the first test, I am making certain that the field is read by reflectively accessing the value contained in the field for the instance of PlainOldJavaObject. Without violating the integrity of the declared class*, I am confident that the field is being set appropriately.

In the second test, I assume that the value has already been set to something prior, so the set-up involves populating the field with a known default value. When I read the value back, I am asserting that the value read back is the value that we know it was originally set to.

Ultimately, if you have a lot of setters and getters, you’ll have to do code like this (since, if you rely on the assumption that your setters and getters “just work”, like you are in your tests above, your test cases may be invalid).

*: Mind you, reflection is a quick and fast way to get into extreme trouble with undefined behavior, and you have few guarantees of object immutability. You’re taking the shrink wrap off of the language and are doing strange and unusual things. Proceed at your own peril.

Leave a Comment