Home > Mobile >  Implement Retry Logic To API Calls
Implement Retry Logic To API Calls

Time:12-08

I'm a junior in QA Automation. I want to assert status code return (expected status 200). However, this request can return status code 200 or 500. My leader suggests that in this case, we need to implement "retry logic" in Java. After 5 unsuccessful retries, we assert status code return.

Need someone suggest me how to do it? Thanks.

CodePudding user response:

It sounds like you want to retry a request in your Java code until it returns a successful status code (200), or until it has been retried a certain number of times (5). Here is an example of how you could implement this using a while loop:

int numRetries = 0;
int maxRetries = 5;
int statusCode = 0;

while (statusCode != 200 && numRetries < maxRetries) {
    // Send the request and get the status code
    statusCode = sendRequest();
    numRetries  ;
}

// At this point, the request has been retried the maximum number of times
// or it has returned a successful status code.
// You can now assert the status code.
assertEquals(200, statusCode);

In this code, the sendRequest method would be responsible for sending the request and returning the status code. If the request returns a status code other than 200, the while loop will continue to retry the request until either it returns a successful status code or the maximum number of retries is reached.

  • Related