Mockito How to mock and assert a thrown exception?

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

    Using mockito, you can make the exception happen.

    when(testingClassObj.testSomeMethod).thenThrow(new CustomException());

    Using Junit5, you can assert exception, asserts whether that exception is thrown when testing method is invoked.

    @Test
    @DisplayName("Test assert exception")
    void testCustomException(TestInfo testInfo) {
        final ExpectCustomException expectEx = new ExpectCustomException();
    
         InvalidParameterCountException exception = assertThrows(InvalidParameterCountException.class, () -> {
                expectEx.constructErrorMessage("sample ","error");
            });
        assertEquals("Invalid parametercount: expected=3, passed=2", exception.getMessage());
    }
    

    Find a sample here: assert exception junit

提交回复
热议问题