Mockito How to mock and assert a thrown exception?

后端 未结 11 1276
既然无缘
既然无缘 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:25

    Make the exception happen like this:

    when(obj.someMethod()).thenThrow(new AnException());
    

    Verify it has happened either by asserting that your test will throw such an exception:

    @Test(expected = AnException.class)
    

    Or by normal mock verification:

    verify(obj).someMethod();
    

    The latter option is required if your test is designed to prove intermediate code handles the exception (i.e. the exception won't be thrown from your test method).

提交回复
热议问题