该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());
但该演员表看起来很“丑陋”,并且可以解决一些缺陷。我可以以“更精细”的方式(即不使用强制转换)进行编译吗?
问题在中Assertions
,它声明AbstractThrowableAssert<?, ? extends Throwable> assertThat(Throwable t)
而不是<T> AbstractThrowableAssert<?, T extends Throwable> assertThat(T t)
但是很遗憾,由于以下现有方法与之冲突,因此无法完成此操作:public static <T> ObjectAssert<T> assertThat(T actual)
。
铸造是一种解决方案,我同意这不是超级优雅。
在这种情况下,我要做的只是:
assertThat(myCustomException.isMyCustomFieldSet()).isTrue();
或myCustomException
直接声明:
assertThat(myCustomException).hasFieldOrPropertyWithValue("myCustomFieldSet", true)
.hasFieldOrPropertyWithValue("myOtherField", "foo");
此处的缺点是按名称访问字段,这对重构不友好。