How to mock 3rd API response when 1st API and 2nd API is working on test environment

Viewed 39

I have 3 microservices Want to mock last ms api response.

Ex: my 1st api sends the correct request. And some fields are used in the 2nd MS API to send the request to 3rd MS API.

Now I want to send 403 from the 3rd MS api.

1 Answers

You can use Wiremock for this case. It's a library for stubbing and mocking web services.

This is the example of basic usage:

int port = 8080;
WireMockServer wireMockServer = new WireMockServer(port);
wireMockServer.start();

stubFor(get(urlEqualTo("/ms/api/v3"))
        .willReturn(aResponse()
                .withStatus(HttpStatus.FORBIDDEN.value())));

// after completing all your tests
wireMockServer.shutdown();

Firstly, you configure your WireMock server. Then you specify the stub for a specific URL. After all the work you should also shut down the server.

If you're using the Spring framework and JUnit, it might be a good idea to set up the WireMock server as a Spring-manged bean. This will remove a lot of overhead. Please see my configuration example below:

import com.github.tomakehurst.wiremock.WireMockServer;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;

@TestConfiguration
public class WiremockConfig {
    private static final Integer WIREMOCK_PORT = 8080;

    @Bean(initMethod = "start", destroyMethod = "stop")
    public WireMockServer wireMockServer() {
        return new WireMockServer(WIREMOCK_PORT);
    }
}

Dependencies you may need:

<dependency>
    <groupId>com.github.tomakehurst</groupId>
    <artifactId>wiremock</artifactId>
    <version>2.27.2</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.github.tomakehurst</groupId>
    <artifactId>wiremock-jre8-standalone</artifactId>
    <version>2.32.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>de.mkammerer.wiremock-junit5</groupId>
    <artifactId>wiremock-junit5</artifactId>
    <version>1.1.0</version>
    <scope>test</scope>
</dependency>
Related