Mockito How to Mock and Assert a Thrown Exception?

I'm using mockito in a junit test. How do you make an exception happen and then assert that it has (generic pseudo-code)

0

12 Answers

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

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

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.