gpt4 book ai didi

java - 使用 wiremock 时返回自定义异常

转载 作者:行者123 更新时间:2023-12-05 03:41:14 26 4
gpt4 key购买 nike

我需要在模拟 url 时返回自定义异常

每当我点击/test/user/get/时,我都需要返回 UserNotFoundException。

我正在尝试这样做。有人可以帮我如何在 wiremock 中返回异常

 public void setupWiresMockStubs(String body, int status) {
wireMockServer.stubFor(post(urlEqualTo(
"/test/user/get"))
.willReturn(aResponse().withHeader("Content-Type", "application/json")
.withBody(body)
.withStatus(status)));
}

最佳答案

您不能返回异常。 API 应返回状态代码和正文。

假设您的 API 在出现异常 UserNotFoundException 时返回 BadRequest(http 代码 400):

@PostMapping(value = "/test/user/get")
public String myApi(@RequestParam String param1) {
try {...
} catch(UserNotFoundException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "user not found");

您可以通过这种方式模拟上述 API:

WireMock.stubFor(WireMock.post(WireMock.urlPathEqualTo("/test/user/get"))
.willReturn(aResponse().withStatus(400).withBody("user not found")));

甚至更好 - Wiremock 中有预定义错误 (ResponseDefinitionBuilder):

WireMock.stubFor(WireMock.post(WireMock.urlPathEqualTo("/test/user/get"))
.willReturn(badRequest().withBody("user not found")));

Wiremock 中存在各种预定义错误:

badRequest(), unauthorized(), notFound() etc.

https://github.com/wiremock/wiremock/blob/master/src/main/java/com/github/tomakehurst/wiremock/client/WireMock.java#L602

关于java - 使用 wiremock 时返回自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67846818/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com