Mockito How to mock and assert a thrown exception?

后端 未结 11 1249
既然无缘
既然无缘 2020-12-02 05:45

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

11条回答
  •  攒了一身酷
    2020-12-02 06:41

    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

    • Mockito + Catch-Exception + Assertj full sample

    Dependencies

    • eu.codearte.catch-exception:catch-exception:2.0
    • org.assertj:assertj-core:3.12.2

提交回复
热议问题