如何为这个类编写单元测试

时间:2015-07-17 10:56:01

标签: java unit-testing junit

我需要为这段代码编写单元测试。我正在学习如何编写单元测试。我想知道可以为下面的课程编写的测试用例是什么

public void delay() 

方法。它包含Thread.sleep()方法。

 import org.apache.log4j.Logger;

public abstract class AbstractDelayService<T> implements DelayService<T>
{
  private static Logger log = Logger.getLogger(AbstractDelayServiceTest.class);

  protected DelayFunction delayFunction;
  protected FailureCounter<T> failureCounter;

  public AbstractDelayService(DelayFunction delayFunction, FailureCounter<T> failureCouner)
  {
    this.delayFunction = delayFunction;
    this.failureCounter = failureCouner;
  }

  @Override
  public void delay()
  {
    long delay = delayFunction.getDelay();
    log.info("Delaying lookup of" + " by " + delay + " ms");

    try
    {
      Thread.sleep(delay);
    }
    catch (InterruptedException e)
    {
      e.printStackTrace();
    }
  }

  @Override
  public void reportSendSuccess(T key)
  {
    failureCounter.reportSendSuccess(key);   
  }

  @Override
  public void reportSendFailure(T key)
  {
    failureCounter.reportSendFailure(key);    
  }

}

1 个答案:

答案 0 :(得分:1)

你明确地不想等待真实使用Thread.sleep,然后计算已经过了多长时间 - 它是缓慢且不可靠的。您必须向被测试的类注入Sleeper接口,因此您可以在测试中模拟我。例如:

interface Sleeper {
    void sleep(long ms) throws InterruptedException;
}

...

class RealSleeper implements Sleeper {
    void sleep(long ms) throws InterruptedException {
        Thread.sleep(ms);
    }
}

...

private long time = 0;

@Test
public void test() {
    AbstractDelayService service = new AbstractDelayService(new Sleeper(){
        void sleep(long ms) {
            time+=ms;
        }, delayFunction, failureCouner){};
    Assert.assertEquals(time, 0);
    service.delay();
    Assert.assertEquals(time, 1000);
}

通过这种方式,您可以验证您的课程完全符合预期。 您仍然需要进行一些集成测试以确保实际调用Thread.sleep - 但您不必在此类测试中长时间睡眠而且您不需要测量确切的时间。