I am having a class which uses RetryTemplate. Whenever there is connection issue the RetryTemplate inside retryConnection() is called and try to call method checkUser() again.
private List<String> retryConnection() throws Exception {
RetryTemplate retryTemplate = new RetryTemplate();
FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
fixedBackOffPolicy.setBackOffPeriod(2000l);
retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
final String[][] user = new String[1][1];
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(2);
retryTemplate.setRetryPolicy(retryPolicy);
try {
retryTemplate.execute(new RetryCallback<Object>() {
@Override
public Object doWithRetry(RetryContext retryContext) throws Exception {
if (retryContext.getRetryCount() < 2) { // unexpected disconnection
throw new RuntimeException("retry exception");
}
user[0] = checkUser();
System.out.println("RETRY" + retryContext);
return null;
}
});
} catch (Exception e) {
e.printStackTrace();
}
return Arrays.asList(user[0]);
}
I now need to create a JUNIT class for testing this method. Whenever exception is detected in the test class the RetryTemplate should be called which in turn calls the checkUser() method. Not sure how to implement this in test class. Please note EasyMock is available for JUnit testing.
I have created a test class as below. Not sure if it's in a right direction.
private List<String> retryConnection() throws Exception {
RetryTemplate mockRetry = EasyMock.createMock(RetryTemplate.class);
RetryCallback callback;
try{
//do something
fail("Expected Exception");
}catch (Exception e){
try {
EasyMock.expect(mockRetry.execute((RetryCallback<Object>) RetryContext::getRetryCount)).andReturn(2);
EasyMock.expect(mockRetry.execute((RetryCallback<Object>) RetryContext::getLastThrowable)).andReturn(Exception.class);
} catch (Exception e) {
e.printStackTrace();
}
}
}