When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.
If you want to test a scenario in which an exception should be thrown then you should use the expected annotation. If you want to test a scenario where your code fails and you want to see if the error is correctly handled: use expected and perhaps use asserts to determine if it's been resolved.
In order to test the exception thrown by any method in JUnit 4, you need to use @Test(expected=IllegalArgumentException. class) annotation. You can replace IllegalArgumentException. class with any other exception e.g. NullPointerException.
To answer your second question first. If you're using JUnit 4, you can annotate your test with
@Test(expected=MyException.class)
to assert that an exception has occured. And to "mock" an exception with mockito, use
when(myMock.doSomething()).thenThrow(new MyException());
Mockito alone is not the best solution for handling exceptions, use Mockito with Catch-Exception
given(otherServiceMock.bar()).willThrow(new MyException());
when(() -> myService.foo());
then(caughtException()).isInstanceOf(MyException.class);
If you want to test the exception message as well you can use JUnit's ExpectedException with Mockito:
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void testExceptionMessage() throws Exception {
expectedException.expect(AnyException.class);
expectedException.expectMessage("The expected message");
given(foo.bar()).willThrow(new AnyException("The expected message"));
}
Updated answer for 06/19/2015 (if you're using java 8)
Just use assertj
Using assertj-core-3.0.0 + Java 8 Lambdas
@Test
public void shouldThrowIllegalArgumentExceptionWhenPassingBadArg() {
assertThatThrownBy(() -> myService.sumTingWong("badArg"))
.isInstanceOf(IllegalArgumentException.class);
}
Reference: http://blog.codeleak.pl/2015/04/junit-testing-exceptions-with-java-8.html
If you're using JUnit 4, and Mockito 1.10.x Annotate your test method with:
@Test(expected = AnyException.class)
and to throw your desired exception use:
Mockito.doThrow(new AnyException()).when(obj).callAnyMethod();
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