方法不适用于参数,可能的异常类型擦除问题?
Method not applicable for the arguments, possible Exception type erasure issue?
我正在使用 Java8 并尝试编写一个测试助手来验证抛出的异常是否属于特定类型。这是一个有效的初始版本:
private static <E extends Exception> void expectThrow(Callable<Void> callable, Class<E> exceptionClass) {
try {
callable.call();
} catch (Exception e) {
assertTrue(exceptionClass.isInstance(e));
}
}
我想做的是用 hamcrest 匹配器替换 catch 块,这样我就可以从失败中获得更多有用的信息:
assertThat(e, Matchers.isA(exceptionClass));
但这不能编译 - 我得到这个可爱的错误:The method assertThat(T, Matcher<? super T>) in the type Assert is not applicable for the arguments (Exception, Matcher<E>)
这让我感到困惑 - 这不应该有效吗?这似乎类似于以下情况,它工作得很好:
Integer a = 3;
assertThat(a, Matchers.isA(Number.class));
经过一番尝试后,以下方法也有效:
assertThat((E)e, Matchers.isA(exceptionClass));
虽然这给了我一个有用的 "unchecked cast from Exception to E" 类型的安全警告。我知道我不能 catch (E e)
- 键入擦除和所有...
这是怎么回事?如何以类型安全的方式更新我的测试助手?
这似乎是 long-standing issue 5 天前终于修复的问题。 isA
的签名已损坏。在 Hamcrest 的下一个版本提供修复程序之前,并且在您的项目使用该版本之前,您必须使用
assertThat(e, is(instanceOf(exceptionClass)))
我正在使用 Java8 并尝试编写一个测试助手来验证抛出的异常是否属于特定类型。这是一个有效的初始版本:
private static <E extends Exception> void expectThrow(Callable<Void> callable, Class<E> exceptionClass) {
try {
callable.call();
} catch (Exception e) {
assertTrue(exceptionClass.isInstance(e));
}
}
我想做的是用 hamcrest 匹配器替换 catch 块,这样我就可以从失败中获得更多有用的信息:
assertThat(e, Matchers.isA(exceptionClass));
但这不能编译 - 我得到这个可爱的错误:The method assertThat(T, Matcher<? super T>) in the type Assert is not applicable for the arguments (Exception, Matcher<E>)
这让我感到困惑 - 这不应该有效吗?这似乎类似于以下情况,它工作得很好:
Integer a = 3;
assertThat(a, Matchers.isA(Number.class));
经过一番尝试后,以下方法也有效:
assertThat((E)e, Matchers.isA(exceptionClass));
虽然这给了我一个有用的 "unchecked cast from Exception to E" 类型的安全警告。我知道我不能 catch (E e)
- 键入擦除和所有...
这是怎么回事?如何以类型安全的方式更新我的测试助手?
这似乎是 long-standing issue 5 天前终于修复的问题。 isA
的签名已损坏。在 Hamcrest 的下一个版本提供修复程序之前,并且在您的项目使用该版本之前,您必须使用
assertThat(e, is(instanceOf(exceptionClass)))