我想測試,如果我的方法調用被重試幾次,如果發生一些異常。如果我直接調用方法,它可以正常工作。但是如果我在單獨的線程中調用它,我的測試方法失敗,它不會看到任何重試嘗試。 這是我的方法:Retryable不能在單獨的線程中工作
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線程):
@Retryable(value = {Exception.class}, maxAttempts = 5, backoff = @Backoff(delay = 30000))
public void retryMethod(Integer id, double dId)
{
service.updateIndex(id, dId);
}
,我的測試方法運行正常。什麼是錯誤?
你的測試是錯誤的。你嘲笑事物並自己創建一個新實例(基本上'@ Inject'是無用的),因此'@Retry'什麼也不做。 –
我正在使用測試春天上下文並注入很好的作品。我的測試適用於多線程輸入。 – Sviatlana
不,它不會...... @ @ InjectMocks呈現@ @ Inject無用,因爲它會構造一個新實例,並將嘲諷的依賴注入到它中。它不會使用Spring注入的實例。因此你的測試是錯誤的。 –