使用junit @Rule和hamcrest匹配器来断定原因异常消息

时间:2019-05-02 08:04:44

标签: exception junit mockito hamcrest

要测试异常,我可以使用以下内容:

@org.junit.Rule
public ExpectedException expectedException = ExpectedException.none();

// and in my test:
expectedException.expect(MyException.class
expectedException.expectMessage("some message");

但是我想测试异常的原因,并且我一直在努力寻找解决方法。现在,我有以下内容:

expectedException.expectCause(
     org.junit.internal.matchers.ThrowableCauseMatcher.hasCause(
        org.mockito.ArgumentMatchers.argThat((e) -> {
           assertEquals(
           "Unexpected message",
           "the message of the cause",
           ((SomeOtherException)e).getCause().getMessage());

           return true;
        })));

但这给了我

  

java.lang.NullPointerException       在org.junit.internal.matchers.ThrowableCauseMatcher.matchesSafely(ThrowableCauseMatcher.java:30)       在org.junit.internal.matchers.ThrowableCauseMatcher.matchesSafely(ThrowableCauseMatcher.java:14)       在org.hamcrest.TypeSafeMatcher.matches(TypeSafeMatcher.java:65)

有人知道正确的方法吗?

0 个答案:

没有答案