简体   繁体   English

如何对与Thread.interrupt一起使用的代码进行可重复的单元测试?

[英]How to make repeatable unit tests of code that works with Thread.interrupt?

Consider some code that calls, say, 考虑一些代码,例如,

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

and wants to handle a ClosedByInterruptException circumstance. 并希望处理ClosedByInterruptException情况。 I'm stumped by how to make a realistic, repeatable unit test. 我对如何进行现实的,可重复的单元测试感到困惑。

To make a test, I need to somehow synchronize this thread with some other thread, and cause the other thread to call Thread#interrupt at the right time. 为了进行测试,我需要以某种方式将该线程与其他线程进行同步,并使另一个线程在正确的时间调用Thread#interrupt。 However, all the primitives for waiting are, well, interruptible, and clear out the interrupt. 但是,所有等待的原语都是可中断的,并且可以清除中断。

For now I've got Thread.currentThread().interrupt in the code being tested (as requested by the unit test), but this isn't really quite the same thing as an actual async interrupt, is it? 现在,我正在测试的代码中有Thread.currentThread()。interrupt(根据单元测试的要求),但这与实际的异步中断并不完全相同,不是吗?

The thing you are interested in testing is the handling of the exception, rather than the details of creating it. 您对测试感兴趣的是异常的处理,而不是创建异常的细节。 You could move the relevant code into another method, then override that method for testing and throw the relevant exception. 您可以将相关代码移到另一个方法中,然后重写该方法进行测试并引发相关异常。 You are then able to test the results without worrying about threading issues. 这样,您就可以测试结果,而不必担心线程问题。

For example: 例如:

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

        ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM