1

考虑一些调用的代码,比如说,

 file = new RandomAccessFile(x, "r");
 file.getChannel().map(....)

并且想要处理 ClosedByInterruptException 情况。我对如何进行现实的、可重复的单元测试感到困惑。

为了进行测试,我需要以某种方式将此线程与其他线程同步,并导致其他线程在正确的时间调用 Thread#interrupt。但是,所有等待的原语都是可中断的,并且可以清除中断。

现在我在正在测试的代码中有 Thread.currentThread().interrupt(根据单元测试的要求),但这与实际的异步中断并不完全相同,是吗?

4

1 回答 1

3

您对测试感兴趣的是异常的处理,而不是创建它的细节。您可以将相关代码移动到另一个方法中,然后覆盖该方法进行测试并抛出相关异常。然后,您可以测试结果而不必担心线程问题。

例如:

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(...);
            }
        };

        ...
    }
}
于 2009-07-22T14:28:53.970 回答