java - 匹配自定义异常

标签 java assertj

Javadocmatches 方法给出了这个例子:

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/

相关文章:

java - 使用assertJ方法 containsOnly() 比较自定义对象的数组

java - 使用assertj时是否可以记录被断言的字段的名称和值以及条件?

java - Android Studio 和 Eclipse

java - 使用 JUnit @Rule 使用 Mockito 进行参数化测试?

java - thymeleaf 和 spring boot 应用程序中未显示表单验证错误

Java不捕获异常

java - 即使 .class 文件存在,也会出现 java.lang.NoClassDefFoundError 错误

java - 如何在 Java 中向 XML 输出添加回车符

java - 在@SpringBootTest中测试@Async注释的方法

java - Restful BDD : How to loop on Steps with Soft Assertions