Mockito How to mock and assert a thrown exception?

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

    If you want to test the exception message as well you can use JUnit's ExpectedException with Mockito:

    @Rule
    public ExpectedException expectedException = ExpectedException.none();
    
    @Test
    public void testExceptionMessage() throws Exception {
        expectedException.expect(AnyException.class);
        expectedException.expectMessage("The expected message");
    
        given(foo.bar()).willThrow(new AnyException("The expected message"));
    }
    

提交回复
热议问题