javaexceptionjunitmockito

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)


Solution

  • 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