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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Nichole
  • 189
  • 2
  • 7
  • 2
    You are instantiating `RemoteService` yourself, instead of having it instantiated by Spring, which means the `@Retryable` annotation does nothing at all. – Mark Rotteveel Jul 06 '22 at 11:04
  • You need to run the junit with spring instead of `MockitoJUnitRunner` – Smile Jul 06 '22 at 11:06
  • 1
    You can refer to this answer to see what you are doing wrong: https://stackoverflow.com/questions/39478665/springs-retryable-not-working-when-running-junit-test – viggnah Jul 06 '22 at 11:08
  • Does this answer your question? [Spring's @Retryable not working when running JUnit Test](https://stackoverflow.com/questions/39478665/springs-retryable-not-working-when-running-junit-test) – jannis Jul 06 '22 at 21:35

0 Answers0