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



Question:

Consider some code that calls, say,

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

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?


Solution:1

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »