Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a method using sleep() with Java?

Tags:

java

junit

I have the following method and I am struggling to get 100% code coverage.

public final class SleepingHelper {
    public static void sleepInMillis(Duration timeOfNextTry) {
        try {
            Thread.sleep(timeOfNextTry.toMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

The question is how can I force Thread.sleep to throw an exception?

Edit: since it was marked as duplicate, I am still wondering what I would assert in the test ? The other question Is more generic.

like image 561
Paul Fournel Avatar asked Jan 23 '16 21:01

Paul Fournel


People also ask

How do you test methods in java?

Each test method should have an "annotation" @ Test . This tells the JUnit test framework that this is an executable test method. To run the tests, select the project with the right-mouse button and click Test. Let's add functionality for adding and subtracting to the test class.

What is sleep () method?

sleep() method can be used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can't be negative, else it throws IllegalArgumentException .

How do you check if a thread is sleeping?

You can call Thread. getState() on and check if the state is TIMED_WAITING . Note, however that TIMED_WAITING doesn't necessarily mean that the thread called sleep() , it could also be waiting in a Object.


1 Answers

You need to interrupt it from another thread. For example:

 Thread t = new Thread() {
     public void run () {
        SleeperMillis.sleepInMillis(new Duration(10000000l));
     }
 }.start();
 Thread.sleep(100); // let the other thread start
 t.interrupt;
like image 161
Dima Avatar answered Sep 22 '22 12:09

Dima