Testing with Thread.sleep

后端 未结 6 1787
囚心锁ツ
囚心锁ツ 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:56

    Create some retry delay type that represents the policy for retry delays. Invoke some method on the policy type for the delay. Mock it as you like. No conditional logic, or true/false flags. Just inject the type that you want.

    In ConnectRetryPolicy.java

    public interface ConnectRetryPolicy {
        void doRetryDelay();
    }
    

    In SleepConnectRetryPolicy.java

    public class final SleepConnectRetryPolicy implements ConnectRetryPolicy {
        private final int delay;
        public SleepConnectRetryPolicy(final int delay) {
            this.delay = delay;
        }
    
        @Override
        public void doRetryDelay() {
            try {
                Thread.sleep(delay);
            } catch (InterruptedException ie) {
                log.error("connection delay sleep interrupted", ie);
            }
        }
    }
    

    In MockConnectRetryPolicy.java

    public final class MockConnectRetryPolicy implements ConnectRetryPolicy {    
        @Override
        public void doRetryDelay() {
            // no delay
        }
    }
    

提交回复
热议问题