Mockito How to mock and assert a thrown exception?

stackoverflow picture stackoverflow · Apr 26, 2013 · Viewed 357.1k times · Source

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

Answer

NilsH picture NilsH · Apr 26, 2013

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