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({
    @ConfigureWireMock(name = "user-service", property = "user-client.url")
})
class TodoControllerTests {

    @InjectWireMock("user-service")
    private WireMockServer wiremock;
    
    @Autowired
    private Environment env;

    @Test
    void aTest() {
        // returns a URL to WireMockServer instance
        env.getProperty("user-client.url"); 
        wiremock.stubFor(get("/todolist").willReturn(aResponse()
                .withHeader("Content-Type", "application/json")
                .withBody("""
                        [
                            { "id": 1, "userId": 1, "title": "my todo" },
                        ]
                        """)
        ));
    }
}

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 #