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;
          }
          sleep(ofSeconds(REQUEST_STATUS_CHECK_INTERVAL));
        }
      }, 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);
    }
  }

Answer

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.

sleep(ofSeconds(getSleepInternval()));

In the test would wold call

testedObject.setSleepInterval(0);

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

class Sleeper {
   void sleep(long milisecs) {
     Thread.sleep(milisecs);
   }
}

In your class you would have

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

In the function

sleeper.sleep(ofSeconds(REQUEST_STATUS_CHECK_INTERVAL));

And it the test you can do

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


Source: stackoverflow