Reputation: 43
How can I test method which throws NullPointerException using JUnit 5. But I catch this exception in the method, so test is ending with error: "Expected java.lang.NullPointerException to be thrown, but nothing was thrown."
class MyClass {
void myMethod() {
try {
//do somthing
throw new NullPointerException();
} catch(NullPointerException e) {
//tell about exception
}
}
}
class MyClassTest {
@Test
void shouldThrowNullPointerException() {
MyClass odj = new MyClass();
Assertions.assertThrows(NullPointerException.class, () -> obj.myMethod());
}
}
Thank you
Upvotes: 0
Views: 3545
Reputation: 26340
assertThrows
is meant for uncaught exception. It makes no sense for cases where the method catches the exception. You can not test for that directly. If //do somthing
is doing something that you can observe from outside your method, then you can assert on that (i.e. if your catch block would return null
or some other value to signify that an error occured.
Upvotes: 3