How to stop main method calling sleep() method, when testing it with Junit?

Tags: , , , ,

I am testing a method which contain sleep in side it.What is the way to stop invoke sleep() as it makes testing slow??

  public void fun(Integer timeToWait) {
    TimeLimiter timeLimiter = new SimpleTimeLimiter();
    try {
      timeLimiter.callWithTimeout(() -> {
        while (true) {
          if (avrageIsAboveThanDesired) {
            return true;
      }, timeToWait, TimeUnit.MINUTES, true);
    } catch (UncheckedTimeoutException e) {
      logger.error("Timed out waiting Instances to be in Running State", e);
    } catch (WingsException e) {
      throw e;
    } catch (Exception e) {
      throw new InvalidRequestException("Error while waiting Instaces to be in Running State", e);


There is no easy way for doing this. You have several options.

The easiest one would be to make the REQUEST_STATUS_CHECK_INTERVAL configurable and configure it to 0 in tests. It can be a property of the tested class.


In the test would wold call


Second option would be to extract the sleep call into it’s own class that can be mocked.

class Sleeper {
   void sleep(long milisecs) {

In your class you would have

private Sleeper sleeper = new Sleeper(); //nd it's setter, or dependency injection

In the function


And it the test you can do

Sleeper mockedSleeper = Mockito.mock(Sleeper.class);

Source: stackoverflow