使用Thread.sleep进行测试

not*_*oop 8 java testing unit-testing sleep

使用何种方法Thread.sleep()来加速测试.

我正在测试一个网络库,当连接被删除或发生超时错误时,它具有重试功能.但是,库Thread.sleep()在重试之间使用(因此在服务器重启时它不会连接数千次).这个调用显着减慢了单元测试,我想知道选项是什么来覆盖它.

注意,我愿意实际更改代码,或者使用模拟框架来模拟Thread.sleep(),但是我想先听听您的意见/建议.

Eug*_*hov 13

将与时间相关的功能委托给单独的组件通常是个好主意.这包括获取当前时间,以及像Thread.sleep()这样的延迟.这样,在测试期间很容易用mock替换这个组件,以及切换到不同的实现.

  • 我一直试图创建一个`Machine`类来抽象出所有这些. (2认同)

Wim*_*uwe 6

我刚刚遇到了类似的问题,我创建了一个Sleeper接口来抽象它:

public interface Sleeper
{
    void sleep( long millis ) throws InterruptedException;
}
Run Code Online (Sandbox Code Playgroud)

默认实现使用Thread.sleep()

public class ThreadSleeper implements Sleeper
{
    @Override
    public void sleep( long millis ) throws InterruptedException
    {
        Thread.sleep( millis );
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的单元测试中,我注入了一个FixedDateTimeAdvanceSleeper

public class FixedDateTimeAdvanceSleeper implements Sleeper
{
    @Override
    public void sleep( long millis ) throws InterruptedException
    {
        DateTimeUtils.setCurrentMillisFixed( DateTime.now().getMillis() + millis );
    }
}
Run Code Online (Sandbox Code Playgroud)

这允许我在单元测试中查询时间:

assertThat( new DateTime( DateTimeUtils.currentTimeMillis() ) ).isEqualTo( new DateTime( "2014-03-27T00:00:30" ) );
Run Code Online (Sandbox Code Playgroud)

请注意,您需要DateTimeUtils.setCurrentMillisFixed( new DateTime( "2014-03-26T09:37:13" ).getMillis() );在测试开始时首先使用修复时间,并在测试后使用DateTimeUtils.setCurrentMillisSystem();