Java / Mockito-对线程在重试之前以指数方式睡眠的单元测试

时间:2019-02-06 20:56:59

标签: java spring unit-testing junit mockito

我正在尝试创建一个单元测试类来测试我创建的类。此类尝试发送消息,如果发送失败,它将重试(1s,2s,4s,8s等),然后重试发送消息。我想测试此指数等待行为是否正常工作。但是我是单元测试的新手,并且不确定如何使用JUnit和Mockito对其进行测试。任何帮助将不胜感激!

@Slf4j
@Setter
@RequiredArgsConstructor
@AllArgsConstructor(access = AccessLevel.PACKAGE)
public class RetriableProcessorExponentialDecorator implements      
AbsMessageProcessorDecorator {
private final AbsMessageProcessor messageProcessor;
@Autowired
private AbsMessageActiveMQConfiguration configuration;

@Override
public void onMessage(AbsMessage message) throws Exception {
int executionCounter = 0;
long delay = 1000;
final int maxRetries = this.configuration.getExceptionRetry() + 1;
do {
  executionCounter++;
  try {
    this.messageProcessor.onMessage(message);
  } catch (RetriableException e) {
    log.info("Failed to process message. Retry #{}", executionCounter);
    delay = (long) (delay * (Math.pow(this.configuration.getMultiplier(), executionCounter)));
    Thread.sleep(delay);
  } catch (Exception e) {
    // We don't retry on this, only RetriableException.
    throw e;
  }
  } while (executionCounter < maxRetries && delay < Long.MAX_VALUE);
 }
}

PS根据@Andy Turner的建议,我在我的 RetriableProcessorExponentialDecorator 类中添加了一行private final DefaultSleeper defaultSleeper;,然后将Thread.sleep(delay)替换为defaultSleeper.sleep(delay)

然后,在我的单元测试类中,我通过执行@Mock private DefaultSleeper sleeper;模拟了 DefaultSleeper ,并将模拟对象通过 RetriableProcessorExponentialDecorator 的构造函数传递,如下所示:

@Before
public void setUp() {

this.decorator = new   
RetriableProcessorExponentialDecorator(sleeper, processor,   
configuration);

}

我在正确的轨道上吗?

1 个答案:

答案 0 :(得分:1)

创建如下所示的界面:

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

然后您可以创建此实现:

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

并对其进行模拟:Sleeper sleeper = mock(Sleeper.class);

现在,您可以将其实例注入RetriableProcessorExponentialDecorator中,并在测试中测试与模拟的交互。