I am writing some unit tests for a relatively simple class:
public class Asylum {
List<Guard> guards = new ArrayList<Guard>();
List<Inmate> inmates = new ArrayList<Inmate>();
public void addGuard(Guard g) { //... }
public void addInmate(Inmate i) { //... }
}
My unit tests for these two functions determine what happens if I pass in a null value:
@Test
public void addGuardNullValue() {
asylum.addGuard(null);
assertEquals(0, asylum.getNumGuards());
}
@Test
public void addInmateNullValue() {
asylum.addInmate(null);
assertEquals(0, asylum.getNumInmates());
}
I actually have a few (> 3) of these containers of guards, inmates, wardens, etc. but I would rather not write what is basically the same unit test for all of their classes.
Is there any way I can boil this down to one unit test to cover n classes?
(Please note, I am unable to create an overarching parent class for Guard and Inmate, and I am unable to create an Interface that they both can implement.)
I see only two solutions, and I wouldn’t recommend either.
The first is to use reflection. List all methods in the class and select those with names like
add*orgetNum*. Then you could call theadd*one with a null value and check the return value ofgetNum*. The problem is that you can have false positives in the method names (addGroup) and the resulting test would be hard to read (and write).The second solution would be a method
addPerson(PersonType type, Object person)which downcastspersondepending onPersonType. I find this a terrible option because it removes the static type check, adds unnecessary complexity and is prone to further abuse. I mention because you may find some useful variation.My final answer is “don’t do it, it’s not worth it”. You’ll need more lines, but they are extremely easy to read and write and will probably be bug-free at the first try.
I would like to end with a quote I find fitting: