您对测试感兴趣的是异常的处理,而不是创建它的细节。您可以将相关代码移动到另一个方法中,然后重写该方法进行测试,并抛出相关的异常。然后,您就可以在不担心线程问题的情况下测试结果了。
例如:
public class Foo {
/**
* default scope so it is visible to the test
*/
void doMapping(RandomAccessFile raf) throws ClosedByInterruptException {
file.getChannel().map(....);
}
public void processFile(File x) {
RandomAccessFile raf = new RandomAccessFile(x, "r");
doMapping(raf);
}
...
}
public class FooTest {
@Test
void testProcessFile() {
Foo foo = new Foo() {
@Override
void doMapping(RandomAccessFile raf) throws ClosedByInterruptException {
throw new ClosedByInterruptException(...);
}
};
...
}
}