Mockito How to mock and assert a thrown exception? Mockito How to mock and assert a thrown exception? java java

Mockito How to mock and assert a thrown exception?


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


BDD Style Solution (Updated to Java 8)

Mockito alone is not the best solution for handling exceptions, use Mockito with Catch-Exception

Mockito + Catch-Exception + AssertJ

given(otherServiceMock.bar()).willThrow(new MyException());when(() -> myService.foo());then(caughtException()).isInstanceOf(MyException.class);

Sample code

Dependencies


If you want to test the exception message as well you can use JUnit's ExpectedException with Mockito:

@Rulepublic ExpectedException expectedException = ExpectedException.none();@Testpublic void testExceptionMessage() throws Exception {    expectedException.expect(AnyException.class);    expectedException.expectMessage("The expected message");    given(foo.bar()).willThrow(new AnyException("The expected message"));}