Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock out Thread.sleep() with JMockit?

I have the following code:

class Sleeper {
    public void sleep(long duration) {
        try {
            Thread.sleep(duration);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

How do I test, with JMockit, that Thread.currentThread().interrupt() is called if Thread.sleep() throws an InterruptedException?

like image 867
Noel Yap Avatar asked Aug 16 '11 21:08

Noel Yap


1 Answers

Interesting question. A bit tricky to test because mocking certain methods of java.lang.Thread can interfere with the JRE or with JMockit itself, and because JMockit is (currently) unable to dynamically mock native methods such as sleep. That said, it can still be done:

public void testResetInterruptStatusWhenInterrupted() throws Exception
{
    new Expectations() {
       @Mocked({"sleep", "interrupt"}) final Thread unused = null;

       {
           Thread.sleep(anyLong); result = new InterruptedException();
           onInstance(Thread.currentThread()).interrupt();
       }
    };

    new Sleeper.sleep();
}
like image 109
Rogério Avatar answered Jan 03 '23 15:01

Rogério