How to mock a real running applicaton?

Mehraj Malik :

One of my Microservice [MS1] checks another Microservice [MS2] at startup, if MS2 is running or not. If MS2 is running MS1 will start else fails to start.

But currently I am running MS2 on my local machine which takes a huge amount of RAM ans slow down my machine.

Is there any mechanism so that when MS1 starts and look-up for MS2 it seems that MS2 is running without actually running real MS2?


Update :

Let's assume MS2 is running on localhost:1234 and now MS1 will connect to it using REST.

michalk :

You can have a look at WireMock which is a simulator of HTTP API so it will be suitable for local development. When using it you will be able to mimic a microservice as if it was running as a standalone microservice on given host and port.

You can run it both as a standalone process and as a part of your spring application.

Option 1 - configuring standalone wiremock server :

  1. Download Wiremock Standalone jar
  2. Run standalone server on localhost with port 1234 :
java -jar wiremock-standalone-2.24.0.jar --port 1234
  1. Configure your MS1 microservice to use localhost:1234 as your MS2 host.
  2. Mock your MS2(mocked with wiremock) endpoint with some response :
curl -X POST --data '{ "request": { "url": "/yourendpoint", "method": "GET" }, "response": { "status": 200, "body": "Response" }}' http://localhost:1234/__admin/mappings/new

Here we make a mock that when you hit on your mocked server on /yourendpoint with HTTP GET you will receive text Response as response.

  1. Now when you hit with GET on localhost:1234/yourendpoint you get your mocked response :
curl http://localhost:1234/yourendpoint
Response

Full example can be found at Wiremock Standalone docs


Option 2 - configuring WireMock server in your Spring app :

  1. Add WireMock dependency to your project (watch out to add it not only to test scope)
  2. Create a Spring bean used to set up your server :
@Component
public class CustomMicroserviceMock {

    private WireMockServer wireMockServer;

    public CustomMicroserviceMock() {
        wireMockServer = new WireMockServer(options().port(1234));
        wireMockServer.stubFor(get(urlEqualTo("/yourendpoint"))
                .willReturn(aResponse()
                        .withHeader("Content-Type", "text/plain")
                        .withBody("Response")));
        wireMockServer.start();
    }


    @PreDestroy
    void preDestroy() {
        wireMockServer.stop();
    }

}
  1. When we hit localhost:1234/yourendpoint we get response : Response

This is just a POC how it could look like but it works in both cases.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=311461&siteId=1