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.