I need to return custom exception while mocking a url like
whenever I will hit /test/user/get/ I need to return UserNotFoundException.
I m trying to do like this. Can somebody help me how to return exception in 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)));
}
You cannot return an exception. The API should return a status code and a body.
Let's say your API returns BadRequest (http code 400) in case of exception UserNotFoundException:
@PostMapping(value = "/test/user/get")
public String myApi(@RequestParam String param1) {
try {...
} catch(UserNotFoundException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "user not found");
You can mock the above API this way:
WireMock.stubFor(WireMock.post(WireMock.urlPathEqualTo("/test/user/get"))
.willReturn(aResponse().withStatus(400).withBody("user not found")));
or even better - with predefined errors (ResponseDefinitionBuilder) in Wiremock:
WireMock.stubFor(WireMock.post(WireMock.urlPathEqualTo("/test/user/get"))
.willReturn(badRequest().withBody("user not found")));
You have all kinds of predefined errors in Wiremock:
badRequest(), unauthorized(), notFound() etc.
https://github.com/wiremock/wiremock/blob/master/src/main/java/com/github/tomakehurst/wiremock/client/WireMock.java#L602
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With