3
votes

Let's say I'm testing following method.

/**
 * Does something. This method throws a {@code NullPointerException}
 * either given string or specified charset is {@code null}.
 * @param s the string
 * @param c the charset
 */
void doSomething(String s, Charset c) {
}

How, when I test, can I make mock for a non-null purpose?

assertThrows(NullPointerException.class,
             new MyObject().doSomething(null, UTF_8));
assertThrows(NullPointerException.class,
             new MyObject().doSomething("", null));

Is there any libraries/methods for mocking a general non-null value?

I tried Mockito.mock and it seems throw an Exception for some invalid types for it can actually mock.

Update

By user2004685's answer, now, I'm curious if I can use anyString or any(Class) like this.

assertThrows(NullPointerException.class,
             new MyObject().doSomething(null, any(Charset.class)));
assertThrows(NullPointerException.class,
             new MyObject().doSomething(anyString(), null));
1

1 Answers

1
votes

This is a void method. If you are mocking it using Mockito to throw the Exception then you need to do something like this:

 Mockito.doThrow(new NullPointerException("Description"))
     .when(mymock)
     .doSomething(Mockito.anyString(), Mockito.any(Charset.class));

It should work even if null is passed to the method.