samedi 30 janvier 2016

How can I mock just for a non-null value?

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));

Aucun commentaire:

Enregistrer un commentaire