Mockito How to mock and assert a thrown exception?

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

提交回复
热议问题