【问题标题】:ExpectedException cause of the cause?ExpectedException 原因是什么原因?
【发布时间】:2017-04-10 02:15:58
【问题描述】:

我正在尝试验证我的所有异常是否正确。因为值包含在CompletableFutures 中,所以抛出的异常是ExecutionException,原因是我通常会检查的异常。快速示例:

void foo() throws A {
  try {
    bar();
  } catch B b {
    throw new A(b);
  }
}

所以foo()翻译了bar()抛出的异常,所有这些都在CompletableFuturesAsyncHandlers内部完成(我不会复制整个代码,仅供参考)

在我的单元测试中,我让bar() 抛出一个异常,并想在调用foo() 时检查它是否被正确翻译:

Throwable b = B("bleh");
when(mock.bar()).thenThrow(b);
ExpectedException thrown = ExpectedException.none();
thrown.expect(ExecutionException.class);
thrown.expectCause(Matchers.allOf(
                instanceOf(A.class),
                having(on(A.class).getMessage(),
                        CoreMatchers.is("some message here")),
        ));

到目前为止一切顺利,但我也想验证异常 A 的原因是异常 Bhaving(on(A.class).getCause(), CoreMatchers.is(b)) 导致 CodeGenerationException --> StackOverflowError

TL;DR:我如何获得预期异常的原因?

【问题讨论】:

标签: java junit exception-handling hamcrest expected-exception


【解决方案1】:

试一试,验证原因:

    thrown.expectCause(allOf(
            isA(org.apache.kafka.common.errors.SerializationException.class),
            hasProperty("message", containsString("Error deserializing Avro message for id")),
            hasProperty("cause", allOf(
                    isA(org.apache.avro.AvroTypeException.class),
                    hasProperty("message", containsString("missing required field blabla"))
                    ))
            ));

【讨论】:

    【解决方案2】:

    这是一个我用来测试因果类链的例子。 参考资料:


    import static org.hamcrest.Matchers.contains;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    import org.hamcrest.Description;
    import org.hamcrest.Matcher;
    import org.hamcrest.TypeSafeMatcher;
    import org.junit.Rule;
    import org.junit.Test;
    import org.junit.rules.ExpectedException;
    
    public class CausalClassChainTest {
    
        @Rule
        public ExpectedException expectedException = ExpectedException.none();
    
        @Test
        public void test() throws Exception {
            expectedException.expect(IOException.class);
            expectedException.expectCause(new CausalClassChainMather(Exception.class, RuntimeException.class));
    
            throw new IOException(new Exception(new RuntimeException()));
        }
    
        private static class CausalClassChainMather extends TypeSafeMatcher<Throwable> {
    
            private final Class<? extends Throwable>[] expectedClasses;
            private List<Class<? extends Throwable>> causualClasses;
            private Matcher<Iterable<? extends Class<? extends Throwable>>> matcher;
    
            public CausalClassChainMather(Class<? extends Throwable>... classes) {
                this.expectedClasses = classes;
            }
    
            @Override
            public void describeTo(Description description) {
                // copy of MatcherAssert.assertThat()
                description.appendText("")
                        .appendText("\nExpected: ")
                        .appendDescriptionOf(matcher)
                        .appendText("\n     but: ");
                matcher.describeMismatch(causualClasses, description);
            }
    
            @Override
            protected boolean matchesSafely(Throwable item) {
    
                List<Class<? extends Throwable>> causes = new ArrayList<Class<? extends Throwable>>();
                while (item != null) {
                    causes.add(item.getClass());
                    item = item.getCause();
                }
                causualClasses = Collections.unmodifiableList(causes);
    
                // ordered test
                matcher = contains(expectedClasses);
                return matcher.matches(causualClasses);
            }
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      也许您应该尝试使用简单的hasProperty Matcher,以隔离问题:

      thrown.expectCause(allOf(
                          instanceOf(A.class),
                          hasProperty("message", is("some message here")),
              ));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-08-28
        • 2016-09-01
        • 2011-12-04
        • 2012-07-08
        • 2011-08-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多