可重试不适用于单独的线程

时间:2017-10-16 08:28:17

标签: java spring multithreading junit spring-retry

我正在尝试测试,如果我的方法调用多次重试,如果发生了一些异常。如果我直接调用方法,它可以正常工作。但是,如果我在单独的线程中调用它,我的测试方法失败,它没有看到任何重试尝试。 那是我的方法:

public class MyClass {
        @Inject
        private ServiceClass service;

        @Retryable(value = {Exception.class}, maxAttempts = 5, backoff = @Backoff(delay = 30000))
        public void retryMethod(Integer id, double dId)
        {
            Thread remoteDIUpdater = new Thread(() -> {
            service.updateIndex(id, dId);
            }
            );
        remoteDIUpdater.setDaemon(true);
        remoteDIUpdater.setName("RemoteDIUpdaterThread");
        remoteDIUpdater.start();
        }

        @Recover
        public void recover(Exception ex, Integer id, double dId)
        {
            logger.error("Error", ex);
        }
}

这是我的测试课程:

public class TestClass
{
    @Inject
    @InjectMocks
    private MyClass myClass;

    @Mock     
    private private ServiceClass service;

    @Test
    public void testMethod()
    {
        Integer id = 1;
        double dId = 2d;
        doThrow(Exception.class).when(service).retryMethod(id, dId);
        myClass.updateBetDangerIndex(betId, dangerIndex);
        verify(service, Mockito.times(5)).retryMethod(null, id, iId);
    }

}

也许我的测试方法是错误的。但是,如果我像这样调用我的方法(withot thread):

@Retryable(value = {Exception.class}, maxAttempts = 5, backoff = @Backoff(delay = 30000))
            public void retryMethod(Integer id, double dId)
            {             
                service.updateIndex(id, dId);              
            }

,我的测试方法运行正常。这是什么错误?

1 个答案:

答案 0 :(得分:0)

可能你必须在remoteDIUpdater.start()之后添加Thread.join(),以防止主线程在你的线程之前完成。