Testing with Thread.sleep

后端 未结 6 1786
囚心锁ツ
囚心锁ツ 2021-01-11 16:28

What are the recommended approaches to using Thread.sleep() to speed up tests.

I am testing a network library with a retry functionality when connection

6条回答
  •  礼貌的吻别
    2021-01-11 16:39

    I just faced a similar issue and I created a Sleeper interface to abstract this away:

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

    The default implementation uses Thread.sleep():

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

    In my unit tests, I inject a FixedDateTimeAdvanceSleeper:

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

    This allows me to query the time in a unit test:

    assertThat( new DateTime( DateTimeUtils.currentTimeMillis() ) ).isEqualTo( new DateTime( "2014-03-27T00:00:30" ) );
    

    Note that you need to fix the time first using DateTimeUtils.setCurrentMillisFixed( new DateTime( "2014-03-26T09:37:13" ).getMillis() ); at the start of your test and restore the time again after the test using DateTimeUtils.setCurrentMillisSystem();

提交回复
热议问题