stackoverflow stackoverflow - 1 month ago 13
Java Question

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)

Answer

BDD Style Solution

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

  • eu.codearte.catch-exception:catch-exception:1.3.3
  • org.assertj:assertj-core:1.7.0

Disadvantage

  • Only Mockito up to 1.10.8 is supported
Comments