如何为春季重试逻辑编写单元测试?
我有一个服务类,如下所示,我试图测试重试逻辑
public class RemoteService {
private RestTemplate restTemplate;
@Inject
public RemoteService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Retryable(maxAttempts =3, value = Exception.class, backoff = @Backoff(delay=2000, multiplier = 2))
public List<Accounts> getData() {
try {
List<Account> accounts = restTemplate.exchange("https://accounts/get/data", HttpMethod.POST, getHttpHeaders(),new ParameterizedTypeRefernce<>);
if (accounts == null) {
throw new EmptyAccountsException("No accounts retrieved")'
}
}
catch(Exception ex) {
ex.printStackTrace();
throw ex;
}
return accounts;
}
}
,下面是上述服务的junit,
@RunWith(MockitoJUnitRunner.class)
public class RemoteServiceTest {
private RemoteService remoteService;
@Mock
RestTemplate mockRestTemplate;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
remoteService = new RemoteService(mockRestTemplate);
}
@Test
public void testRetry() {
when(mockRestTemplate.exchange()).thenReturn(null);
remoteService.getData();
verify(mockRestTemplate, times(3)).exchange("https://accounts/get/data", HttpMethod.POST, getHttpHeaders(),new ParameterizedTypeReference<List<Accounts>>);
}
}
在上述测试后,方法getData
未称为3次。它在第一个例外后停止。
请告知这里有什么问题,以及为什么第一次抛出异常时,getData
方法不会被调用3次。
I have a service class as below, for which I am trying to test retry logic
public class RemoteService {
private RestTemplate restTemplate;
@Inject
public RemoteService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Retryable(maxAttempts =3, value = Exception.class, backoff = @Backoff(delay=2000, multiplier = 2))
public List<Accounts> getData() {
try {
List<Account> accounts = restTemplate.exchange("https://accounts/get/data", HttpMethod.POST, getHttpHeaders(),new ParameterizedTypeRefernce<>);
if (accounts == null) {
throw new EmptyAccountsException("No accounts retrieved")'
}
}
catch(Exception ex) {
ex.printStackTrace();
throw ex;
}
return accounts;
}
}
And below is the junit for the above service
@RunWith(MockitoJUnitRunner.class)
public class RemoteServiceTest {
private RemoteService remoteService;
@Mock
RestTemplate mockRestTemplate;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
remoteService = new RemoteService(mockRestTemplate);
}
@Test
public void testRetry() {
when(mockRestTemplate.exchange()).thenReturn(null);
remoteService.getData();
verify(mockRestTemplate, times(3)).exchange("https://accounts/get/data", HttpMethod.POST, getHttpHeaders(),new ParameterizedTypeReference<List<Accounts>>);
}
}
After running test above, the method getData
is not called 3 times. It stops after first exception is thrown.
Please advise what is wrong here and why the getData
method is not called 3 times when exception is thrown for the first time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论