我有以下代码:
Collection<String> errors = ...;
try (InputStream stream = My.class.getResourceAsStream(resource)) {
// do stuff
}
catch(IOException ex) {
errors.add("Fail");
}
当我提供的(有效)输入流应该被关闭时,我正在尝试使用 Byteman Junit Runner 来触发 IOException:
@RunWith(BMUnitRunner.class)
public class MyTest {
private My my = new My();
@BMRule(
name = "force_read_error",
targetClass = "java.io.InputStream",
targetMethod = "close()",
action = "throw new IOException(\"bazinga\")"
)
@Test
public void catches_read_error() throws IOException {
Collection<String> errors = my.foo("/valid-resource-in-classpath");
assertThat(errors).containsExactly("Fail");
}
}
我的测试失败:errors 总是空的,这意味着 Byteman 规则显然没有被执行(它被代理很好地加载,所以我不明白发生了什么)。
如何在通过 try-with-resources 调用的 close 方法上触发 IOException?