如何在使用Junit测试时阻止main方法调用sleep()方法?

huangapple go评论104阅读模式
英文:

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

问题

我正在测试一个包含sleep方法的方法。有什么方法可以停止调用sleep(),因为它会使测试变慢吗?
英文:

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);
    }
  }

答案1

得分: 3

没有简单的方法来做这件事。您有几个选项。

最简单的方法是将REQUEST_STATUS_CHECK_INTERVAL配置为可配置项,并在测试中将其配置为0。它可以是被测试类的属性。

sleep(ofSeconds(getSleepInterval()));

在测试中将调用:

testedObject.setSleepInterval(0);

第二个选项是将睡眠调用提取到它自己的类中,该类可以被模拟。

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

在您的类中,您可以有:

private Sleeper sleeper = new Sleeper(); //以及它的setter,或依赖注入

在函数中:

sleeper.sleep(ofSeconds(REQUEST_STATUS_CHECK_INTERVAL));

在测试中,您可以这样做:

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

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);

huangapple
  • 本文由 发表于 2020年8月8日 21:08:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/63315778.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定