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.gradlebuild.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 bodyWiremockTests.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 ResponseEntityWiremockTests.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();
Full Stack Web Developer in UK,
ReplyDeleteSoftware Development Services London UK,
MOBILE APP DEVELOPMENT SERVICES LONDON,
Mobile App Development Services London UK,
Mobile App Development Service London UK,
Great job. If you want to know more about developmentyou should visit this site where there are many different categories including contract development
ReplyDeleteTHANK U FOR SHARING THIS POST
ReplyDeletecustom software systems
custom web application development services custom web development
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.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteI agree with a lot of the points you made in this article.
ReplyDeleteSAP training in Mumbai
Best SAP training in Mumbai
SAP training institute Mumbai
I appreciate the work you have put into this and hope you continue writing on this subject.
ReplyDeleteSAP training in Kolkata
Best SAP training in Kolkata
SAP training institute in Kolkata
Very good information. Excellent and very useful for all coders. Please check our website for new article Accounting firms in dubai
ReplyDeleteHappy 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
ReplyDeletehttps://kgrnaudit.com/accounting-firms-in-dubai/
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.
ReplyDeleteJava Training in Pune
Thanks for this nice post here.I always like and such a informative contents. Excellent .
ReplyDeleteJava Classes in Pune
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.
ReplyDeleteJava Classes in Pune
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.
ReplyDeleteSoftware testing training in Kolhapur
Software testing course in Pune
nice. Azure Training In Pune
ReplyDeletethanks for shearing this information. Python Course in Amravati
ReplyDeleteGreat Post.
ReplyDeleteJava Classes in Nagpur
amazing writeup. keep posting java classes in pune
ReplyDeleteFirst 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
ReplyDeleteCricut new design dance USA
Looking for commercial loan brokers in Melbourne? Jump Financing helps you find the best loan options with ease. Our expert team makes securing your commercial loan simple and stress-free. Get in touch with us today.
ReplyDeleteLooking for best tax return services in Melbourne? We make filing your taxes easy and stress-free. Our team ensures you get the maximum refund with quick and reliable service.
ReplyDelete