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

Consider some code that calls, say,

 file = new RandomAccessFile(x, "r");

and wants to handle a ClosedByInterruptException circumstance. 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. 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?


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 {

    public void processFile(File x) {
        RandomAccessFile raf = new RandomAccessFile(x, "r");

public class FooTest {
    void testProcessFile() {     
        Foo foo = new Foo() {
            void doMapping(RandomAccessFile raf) throws ClosedByInterruptException {
                throw new ClosedByInterruptException(...);


Leave a Reply

Your email address will not be published. Required fields are marked *