Integrate Wiremock into Spring Boot Java Web Application for Mocking External Dependencies


Introduction

WireMock is a mock server for HTTP-based APIs. Some might consider it a service virtualization tool or a mock server. It enables you to stub out an API or other external dependency you depend on to expedite local development. It supports testing of edge cases and failure modes that the real API won't reliably produce. It also is useful in mocking out external dependencies in unit and integration tests. It has excellent integration with jUnit.

Add Wiremock Dependency

First you will want to add the Wiremock dependency. You can download the regular dependency or the fat JAR stand-alone version that contains all it's dependencies. We will be using the standard dependency here. Add the following dependency to your build.gradle

build.gradle


dependencies {
    testCompile('com.github.tomakehurst:wiremock:2.1.12')
}



Add Wiremock Unit test

Here is the complete unit test that you can use for testing your integration with Wiremock. This unit test uses a jUnit4 rule to spin up a Wiremock server on port 8089 and shut it down after each test. We use the stubFor method to define a mocked end point and the response. We use a Spring RestTemplate to create a HTTP request to our mock server and capture the result.

WiremockTests.java

public class WiremockTests {

    RestTemplate restTemplate;
    ResponseEntity response;

    @Rule
    public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().port(8089).httpsPort(8443));

    @Before
    public void setup() throws Exception {
        restTemplate = new RestTemplate();
        response = null;
    }

    @Test
    public void givenWireMockAdminEndpoint_whenGetWithoutParams_thenVerifyRequest() {

        RestTemplate restTemplate = new RestTemplate();

        response = restTemplate.getForEntity("http://localhost:8089/__admin", String.class);

        assertThat("Verify Response Body", response.getBody().contains("mappings"));
        assertThat("Verify Status Code", response.getStatusCode().equals(HttpStatus.OK));
    }

    @Test
    public void givenWireMockEndpoint_whenGetWithoutParams_thenVerifyRequest() {
        stubFor(get(urlEqualTo("/api/resource/"))
                .willReturn(aResponse()
                        .withStatus(HttpStatus.OK.value())
                        .withHeader("Content-Type", TEXT_PLAIN_VALUE)
                        .withBody("test")));

        response = restTemplate.getForEntity("http://localhost:8089/api/resource/", String.class);

        assertThat("Verify Response Body", response.getBody().contains("test"));
        assertThat("Verify Status Code", response.getStatusCode().equals(HttpStatus.OK));

        verify(getRequestedFor(urlMatching("/api/resource/.*")));
    }
}



Drill down into Unit Test

Here are some static imports you can use for readability and conciseness in your test.

WiremockTests.java

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.springframework.http.MediaType.TEXT_PLAIN_VALUE;



jUnit4 Rule

This jUnit4 @rule will automatically manage the Wiremock server lifecycle and startup and shutdown Wiremock for each test case. You would also be able to implement this using a setup() and teardown() method but the jUnit4 rule is cleaner and more concise.

WiremockTests.java

    @Rule
    public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().port(8089).httpsPort(8443));



Stubbed Endpoint and Response

This code uses the stubFor() method which has been statically imported to define an endpoint, /api/resource/ and the plain text response body "test" You could return a JSON or XML response using this method as well by changing the Content-Type and response body

WiremockTests.java

        stubFor(get(urlEqualTo("/api/resource/"))
                .willReturn(aResponse()
                        .withStatus(HttpStatus.OK.value())
                        .withHeader("Content-Type", TEXT_PLAIN_VALUE)
                        .withBody("test")));



Spring RestTemplate

We use a Spring RestTemplate class to execute a GET HTTP request to http://localhost:8089/api/resource/ hitting the stubbed endpoint of the wiremock server. We are expecting a String.class entity response in this case because that is what we defined in the stubFor() method. You would need to define a POJO object to capture a JSON response from your stubbed out method if that is what you configured. We capture the response in a ResponseEntity object which captures the response body, headers and status code as well as other information about the request.

WiremockTests.java

response = restTemplate.getForEntity("http://localhost:8089/api/resource/", String.class);



Starting and Stopping the Wiremock Server Manually

You can start and stop a Wiremock server manually without using a jUnit4 rule to manage the lifecycle. You may want to do this is a bootstrap method when your application starts up.

ServiceClass.java

WireMockServer wireMockServer = new WireMockServer(wireMockConfig().port(8089)); //No-args constructor will start on port 8080, no HTTPS
wireMockServer.start();

WireMock.reset();

wireMockServer.stop();



Conclusion

You now have Wiremock setup in your project. You can use Wiremock in unit and integration tests to stub externally dependencies and also to speed up development in your local environment. You can read more about setting up Wiremock here: http://wiremock.org/docs/getting-started/

Comments

  1. Great job. If you want to know more about developmentyou should visit this site where there are many different categories including contract development

    ReplyDelete
  2. To have suitable and user-friendly website for your business, you need to find one of the best web Web Design Services in Parramatta. If you are interested then Contact to Visual Supportsoft.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Very good information. Excellent and very useful for all coders. Please check our website for new article Accounting firms in dubai

    ReplyDelete
  5. Happy to read this blog. Thanks for sharing this article. Please check our website for all new article. Also kgrn audit is the one of the best audit firm in UAE. Accounting firms in dubai
    https://kgrnaudit.com/accounting-firms-in-dubai/

    ReplyDelete
  6. I am glad to see this brilliant post. all the details are very helpful and good for us, keep up to good work.I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.
    Java Training in Pune

    ReplyDelete
  7. Thanks for this nice post here.I always like and such a informative contents. Excellent .
    Java Classes in Pune

    ReplyDelete
  8. I recently came across your article and have been reading along. I want to express my admiration of your writing skill and ability to make readers read from the beginning to the end.
    Java Classes in Pune

    ReplyDelete
  9. I am excited to find your excellent content. All of the details are really useful and beneficial for us; keeping up the fantastic work. I found some valuable information in your blog; it was a pleasure to read; thank you for sharing this wonderful stuff with my vision; please continue to share.

    Software testing training in Kolhapur

    Software testing course in Pune

    ReplyDelete

Post a Comment

Popular posts from this blog

Change Port on a Spring Boot Application when using intelliJ

New Personal Website

How to set up a SQL Server 2008 Local Database