I\'m using mockito in a junit test. How do you make an exception happen and then assert that it has (generic pseudo-code)
Use Mockito's doThrow and then catch the desired exception to assert it was thrown later.
@Test
public void fooShouldThrowMyException() {
// given
val myClass = new MyClass();
val arg = mock(MyArgument.class);
doThrow(MyException.class).when(arg).argMethod(any());
Exception exception = null;
// when
try {
myClass.foo(arg);
} catch (MyException t) {
exception = t;
}
// then
assertNotNull(exception);
}
Make the exception happen like this:
when(obj.someMethod()).thenThrow(new AnException());
Verify it has happened either by asserting that your test will throw such an exception:
@Test(expected = AnException.class)
Or by normal mock verification:
verify(obj).someMethod();
The latter option is required if your test is designed to prove intermediate code handles the exception (i.e. the exception won't be thrown from your test method).
Assert by exception message:
try {
MyAgent.getNameByNode("d");
} catch (Exception e) {
Assert.assertEquals("Failed to fetch data.", e.getMessage());
}
Unrelated to mockito, one can catch the exception and assert its properties. To verify that the exception did happen, assert a false condition within the try block after the statement that throws the exception.
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
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);