Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
    }
  }
like image 487
Tathagat Chaurasiya Avatar asked Mar 10 '26 08:03

Tathagat Chaurasiya


1 Answers

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);
like image 57
Pavel Polivka Avatar answered Mar 12 '26 21:03

Pavel Polivka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!