Mockito How to mock and assert a thrown exception?

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

    Use Mockito's doThrow and then catch the desired exception to assert it was thrown later.

    @Test
    public void fooShouldThrowMyException() {
        // given
        val myClass = new MyClass();
        val arg = mock(MyArgument.class);
        doThrow(MyException.class).when(arg).argMethod(any());
        Exception exception = null;
    
        // when
        try {
            myClass.foo(arg);
        } catch (MyException t) {
            exception = t;
        }
    
        // then
        assertNotNull(exception);
    }
    
    0 讨论(0)
  • 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).

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

    Assert by exception message:

        try {
            MyAgent.getNameByNode("d");
        } catch (Exception e) {
            Assert.assertEquals("Failed to fetch data.", e.getMessage());
        }
    
    0 讨论(0)
  • 2020-12-02 06:35

    Unrelated to mockito, one can catch the exception and assert its properties. To verify that the exception did happen, assert a false condition within the try block after the statement that throws the exception.

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

    Updated answer for 06/19/2015 (if you're using java 8)

    Just use assertj

    Using assertj-core-3.0.0 + Java 8 Lambdas

    @Test
    public void shouldThrowIllegalArgumentExceptionWhenPassingBadArg() {
    assertThatThrownBy(() -> myService.sumTingWong("badArg"))
                                      .isInstanceOf(IllegalArgumentException.class);
    }
    

    Reference: http://blog.codeleak.pl/2015/04/junit-testing-exceptions-with-java-8.html

    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题