简体   繁体   中英

How to Write unit tests for this class

I need to write a unit test for this piece of code. I am just learning how to write unit tests.I want to know what are the test cases that can be written for following class specially for

public void delay() 

method. it contains Thread.sleep() method.

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

}

You definitively don't want to wait for real using Thread.sleep and then count how much time elapsed - it's slow and unreliable. You have to inject Sleeper interface to tested class, so you can mock i in tests. For example:

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

This way you can verify your class sleeps exactly as long as it's supposed to. You will still need some integration tests to make sure Thread.sleep is actually invoked - but you don't have to sleep long in such tests and you don't need to measure the exact timings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM