-1

i'm looking for a tool or library that allow me to quickly develop a Spring Boot backend that expose mocked REST services while we're waiting to have specifications about services business logic from our customer.

Are there any best practices? For example reading from JSON files or something else?

Thanks to all

*********************** Additional infos ***********************

  • I want use same server (embedded one) because some API's are already developed.
  • I need a real service response, not test one.
  • I would like to have something more structured than return statement
    return "{
      \"id\": 01,
      \"name\": \"Donald Stumpet\"
    }";
    
DuffMck
  • 81
  • 7
  • 1
    If all you need is to mock responses for REST APIs, rather than creating spring boot backend services, you should try using WireMock. Check it out [here](http://wiremock.org/docs/getting-started/) – Madhu Bhat Jun 26 '20 at 14:26
  • I want use same application server, because some APIs will be implemented later but I already have something developed. – DuffMck Jun 26 '20 at 15:22
  • @DuffMck So how does your scenario look like? Is it like you have API A ->(calling) API B and API C internally. API C is not yet developed and you want to mock it only and you want real response from API B. Is that right? – Abhinaba Chakraborty Jun 26 '20 at 16:39

1 Answers1

1

Wiremock will be your buddy in this case (http://wiremock.org/docs/getting-started/)

In your spring boot test class, setup wiremock rule:

  @Value("${wireMockServer.port}")
  private int wireMockPort;

  private WireMockRule wireMockRule;

  @Rule
  public WireMockRule getWireMockRule() {
    if (wireMockRule == null) {
      wireMockRule = new WireMockRule(wireMockConfig().port(wireMockPort).notifier(new Slf4jNotifier(true)));
    }
    return wireMockRule;
  }

And then just mock your API:

    String url = UriComponentsBuilder
        .fromUriString("XXXXX").buildAndExpand("pathParam1", "pathParamVal").toUriString();

    stubFor(get(urlEqualTo(url))
        .willReturn(aResponse()
            .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
            .withHeader("Connection", "close")
            .withBody(asJson(mockedResponseObject))));

If you want not to programmatically stub your requests and store them in json files , then mention the mappings location with the property wireMock.mappingsUnderClasspath

And inside that directory, create a folder called mappings and put your mapping json files: eg.

{
  "request": {
    "method": "GET",
    "urlPattern": "/foo/myApi"
  },
  "response": {
    "status": 200,
    "headers": {
      "Content-Type": "application/json"
    },
    "bodyFileName": "mockedResponse.json"
  }
}

And keep the mockedResponse.json in a directory called __files (double underscore) inside wireMock.mappingsUnderClasspath

Abhinaba Chakraborty
  • 3,488
  • 2
  • 16
  • 37