To use WireMock with JUnit 4.x you use a @Rule statement to configure the WireMock server:
@Rule
public WireMockRule wireMockRule = new WireMockRule();
With JUnit 5, @Rule was replaced with extensions, so the equivalent setup looks like this:
@RegisterExtension
static WireMockExtension wm1 = WireMockExtension.newInstance()
.options(options().port(8089))
.build();
Testing Spring Boot 3 apps with JUnit 5 however gives the following error as Spring Boot 3 does not have Jetty 11 dependencies, so WireMock’s use of Jetty 11 fails to start:
com.github.tomakehurst.wiremock.common.FatalStartupException: Jetty 11 is not present and no suitable HttpServerFactory extension was found. Please ensure that the classpath includes a WireMock extension that provides an HttpServerFactory implementation. See http://wiremock.org/docs/extending-wiremock/ for more information.
at com.github.tomakehurst.wiremock.WireMockServer.lambda$getHttpServerFactory$2(WireMockServer.java:95)
Per the WireMock docs here, wiremock-spring-boot provides support using another approach. To use, add this dependency:
<dependency>
<groupId>com.maciejwalkowiak.spring</groupId>
<artifactId>wiremock-spring-boot</artifactId>
<version>2.1.2</version>
<scope>test</scope>
</dependency>
Enable for your test by adding @EnableWireMock:
@SpringBootTest
@EnableWireMock({
@ConfigureWireMock(name = "your-mock-service", property = "your-url-to-mock.url")
})
class YourTest {
...
}
Inject the WireMock server into your test with:
@InjectWireMock("your-mock-service")
private WireMockServer wiremock;
@Value("${your-url-to-mock.url}")
private String wiremockUrl;
While this is a neat option to use with SpringBootTests, unfortunately it still doesn’t work with Spring Boot 3.3.x because of WireMock’s dependency on Jetty 11.
Tickets posted on the wiremock-spring-boot project suggest to avoid this in the meantime by using a dependency for wiremock-standalone instead:
<dependency>
<groupId>com.maciejwalkowiak.spring</groupId>
<artifactId>wiremock-spring-boot</artifactId>
<version>2.0.0</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.wiremock</groupId>
<artifactId>wiremock</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wiremock</groupId>
<artifactId>wiremock-standalone</artifactId>
<version>3.3.1</version>
<scope>test</scope>
</dependency>
This works as expected.