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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With