Mockito How to mock and assert a thrown exception?

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

    To answer your second question first. If you're using JUnit 4, you can annotate your test with

    @Test(expected=MyException.class)
    

    to assert that an exception has occured. And to "mock" an exception with mockito, use

    when(myMock.doSomething()).thenThrow(new MyException());
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-02 06:46

    If you're using JUnit 4, and Mockito 1.10.x Annotate your test method with:

    @Test(expected = AnyException.class)
    

    and to throw your desired exception use:

    Mockito.doThrow(new AnyException()).when(obj).callAnyMethod();
    
    0 讨论(0)
  • 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"));
    }
    
    0 讨论(0)
  • 2020-12-02 06:48

    Or if your exception is thrown from the constructor of a class:

    @Rule
    public ExpectedException exception = ExpectedException.none();
    
    @Test
    public void myTest() {    
    
        exception.expect(MyException.class);
        CustomClass myClass= mock(CustomClass.class);
        doThrow(new MyException("constructor failed")).when(myClass);  
    
    }
    
    0 讨论(0)
提交回复
热议问题