I would like to write a junit test case for spring retry, i tried like the below, but the junit is not working as expected. I am calling MaxAttemptRetryService.retry method, if it fails, it has to try for max 3 times. Here, Dao is calling a rest service, that is down, hence it should go trying for maximum 3 times. hence dao.sam method must be called 3 times.
Service Class:
@Service
@EnableRetry
public class MaxAttemptRetryService {
@Retryable(maxAttempts=3)
public String retry(String username) throws Exception {
System.out.println("retry???? am retrying...");
int h = maxAttemptDao.sam();
return "kkkk";
}
}
Dao class:
@Component
public class MaxAttemptDao {
public int sam() throws Exception{
try{
new RestTemplate()
.getForObject("http://localhost:8080/greeting1/{userName}",
String.class, "");
}catch(Exception e){
throw e;
}
return 0;
}
}
Test class:
@RunWith(SpringRunner.class)
public class HystrixServiceTest {
@InjectMocks
private MaxAttemptRetryService maxAttemptRetryService = new MaxAttemptRetryService();
@Mock
private MaxAttemptDao maxAttemptDao;
@Test
public void ff() throws Exception{
when(maxAttemptDao.sam()).thenThrow(Exception.class);
maxAttemptRetryService.retry("ll");
verify(maxAttemptDao, times(3)).sam();
}
}