Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cover a void method that avoids null parameters by passing a null parameter?

I have a method like this:

public class SomeService {
    public void sortByFieldX(List<MyClass> list) {
        if (list != null) {
            Collections.sort(list, new ComparatorOfMyClassThatUsesFieldX());
        }
    }
}

How should I write a test for sortByFieldX where I pass null argument?

public class SomeServiceTest {
    @Test
    public void sortByFieldX() {
        List<MyClass> list = null;
        SomeService service = new SomeService();
        service.sortByFieldX(list);
        //assert what?
        //assertNull(list); is really stupid because Java is pass by value
    }
}

Is this test even valid? I'm just trying to write this test as part of a set of tests to cover all the branches in code.

like image 252
Luiggi Mendoza Avatar asked Dec 03 '25 02:12

Luiggi Mendoza


1 Answers

If you pass a null argument the method does nothing - it doesn't modify any argument (since it's a null), it doesn't return anything (since its a void method), it doesn't update any data member or throw any exception.

IMHO, it's a bit pointless to test such a case, but if you want to be on the safe side, the only thing to test here is that a null input doesn't generate an exception (specifically, a NullPointerException). The test you've provided indeed achieves this goal. As you noted inline, asserting that null is in fact null is pointless.

EDIT:
As per Brois the Spider's suggestion in the comments, this behavior can be made more explicit by using the ExpectedException rule:

public class SomeServiceTest {
    @Rule
    public ExpectedException thrown= ExpectedException.none();

    /** Just makes sure no exception is thrown */
    @Test
    public void sortByFieldX() {
        List<MyClass> list = null;
        SomeService service = new SomeService();
        service.sortByFieldX(list);
    }
}
like image 180
Mureinik Avatar answered Dec 05 '25 16:12

Mureinik