Javadoc为 matches
方法给出了这个例子:
assertThat(player).matches(p -> p.isRookie());
事实上,当我定义一个虚拟类 Player 时,上面的语句编译正常。但是,当我定义一个派生自 Exception 的类时,以下代码无法编译:
public class MyCustomException extends Exception {
public boolean isMyCustomFieldSet() { return true; }
}
...
MyCustomException myCustomException = new MyCustomExcpetion();
assertThat(myCustomException).matches(e -> e.isMyCustomFieldSet());
我可以使用强制转换使其编译:
assertThat(myCustomException).matches(e -> ((MyCustomException)e).isMyCustomFieldSet());
但该 Actor 阵容看起来“丑陋”,并且有点难以解决某种缺陷。我能否以“更好”的方式编译它,即不使用强制转换?
最佳答案
问题在Assertions
, 它声明 AbstractThrowableAssert<?, ? extends Throwable> assertThat(Throwable t)
而不是 <T> AbstractThrowableAssert<?, T extends Throwable> assertThat(T t)
但不幸的是,由于以下现有方法与之冲突,这无法完成:public static <T> ObjectAssert<T> assertThat(T actual)
.
转换是一种解决方案,我同意它不是 super 优雅。
在那种情况下我会做的很简单:
assertThat(myCustomException.isMyCustomFieldSet()).isTrue();
或者在 myCustomException
上保持断言直接:
assertThat(myCustomException).hasFieldOrPropertyWithValue("myCustomFieldSet", true)
.hasFieldOrPropertyWithValue("myOtherField", "foo");
这里的缺点是按名称访问字段,这对重构不友好。
关于java - 匹配自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60001823/