3

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)));
      }
alka kumari
  • 51
  • 1
  • 7
  • Can you elaborate on what you mean by returning this exception? WireMock works as an HTTP/S mock server, so there shouldn't be any "exceptions" thrown by WireMock itself - it should serve up responses with various status codes (which your app may interpret as exceptions or errors). I'm also assuming that your real API doesn't throw an exception -- that'd be designed extremely poorly. Instead, your app probably throws the exception _based on the API response_. – agoff Jun 07 '21 at 13:12

1 Answers1

3

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

Mykeul
  • 498
  • 1
  • 6
  • 20