Using WireMock with Spring Boot
Disclaimer: This solution page includes resources maintained by their authors outside the WireMock organization on GitHub. The info is provided as is without guarantees unless explicitly specified. Referenced projects and guidelines might be incompatible with the recent WireMock 3.x releases or the recent versions of the target technology or framework.
Please use with caution, and submit GitHub issues or pull requests to this page and referenced repositories if something is missing, broken or needs update.
WireMock Spring Boot #
WireMock Spring Boot simplifies testing HTTP clients in Spring Boot & Junit 5 based integration tests. It includes fully declarative WireMock setup, supports multiple WireMockServer
instances, automatically sets Spring environment properties, and does not pollute Spring application context with extra beans.
Example:
@SpringBootTest
@EnableWireMock
class DefaultInstanceTest {
@Value("${wiremock.server.baseUrl}")
private String wiremockUrl;
@Test
void returnsTodos() {
WireMock.stubFor(get("/ping")
.willReturn(aResponse()
.withStatus(200)));
RestAssured
.when()
.get(this.wiremockUrl + "/ping")
.then()
.statusCode(200);
}
}
Spring Cloud Contract #
The team behind Spring Cloud Contract have created a library to support running WireMock using the “ambient” HTTP server. It also simplifies some aspects of configuration and eliminates some common issues that occur when running Spring Boot and WireMock together.
See Spring Cloud Contract WireMock for details.
The article Faking OAuth2 Single Sign-on in Spring from Pivotal’s blog shows how WireMock can be used to test Spring apps that use 3rd party OAuth2 login.
Jetty version issues when running WireMock and Spring together. #
WireMock’s main artifact is built on Jetty 11, largely so that Java 11 support can be maintained. However, many Spring applications depend on Jetty 12 and the presence of both on the classpath causes WireMock to fail with a ClassNotFoundException
or NoClassDefFoundError
for Servlet API classes thrown during startup.
To rectify this, WireMock now has a dedicated Jetty 12 artifact which can be added to your project’s classpath. See the Jetty 12 page for details.
Useful pages #
- WireMock on Java and JVM - Most of JVM generic solutions are applicable to Spring Boot development too