【问题标题】:Implement Retry Logic To API Calls对 API 调用实施重试逻辑
【发布时间】:2022-12-08 06:15:41
【问题描述】:

我是 QA Automation 的大三学生。我想断言状态代码返回(预期状态 200)。但是,此请求可以返回状态代码 200 或 500。 我的领导建议,在这种情况下,我们需要在 Java 中实现“重试逻辑”。 5 次重试不成功后,我们断言返回状态代码。

需要有人建议我怎么做吗?谢谢。

【问题讨论】:

  • 你在这方面有什么困难,确切地说?
  • 是不是我需要在执行 5 次的 for 循环中编写代码?
  • 循环不会总是执行 5 次——您可能会提前执行 200 次。你想在请求之间稍等一下吗?

标签: java api rest automation


【解决方案1】:

听起来您想在 Java 代码中重试请求,直到它返回成功的状态代码 (200),或者直到重试一定次数 (5)。以下是如何使用 while 循环实现此功能的示例:

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);

在此代码中,sendRequest 方法将负责发送请求并返回状态代码。如果请求返回 200 以外的状态代码,while 循环将继续重试请求,直到它返回成功的状态代码或达到最大重试次数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2022-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    相关资源
    最近更新 更多