WireMock and Spring MVC Mocks
Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into a Spring MockRestServiceServer
. Here’s an example:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.NONE)
public class WiremockForDocsMockServerApplicationTests {
@Autowired
private RestTemplate restTemplate;
@Autowired
private Service service;
@Test
public void contextLoads() throws Exception {
// will read stubs classpath
MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate)
.baseUrl("http://example.org").stubs("classpath:/stubs/resource.json")
.build();
// We're asserting if WireMock responded properly
assertThat(this.service.go()).isEqualTo("Hello World");
server.verify();
}
}
The baseUrl
is prepended to all mock calls, and the stubs()
method takes a stub path resource pattern as an argument. So in this example the stub defined at /stubs/resource.json
is loaded into the mock server, so if the RestTemplate
is asked to visit [http://example.org/](http://example.org/)
it will get the responses as declared there. More than one stub pattern can be specified, and each one can be a directory (for a recursive list of all ".json"), or a fixed filename (like in the example above) or an ant-style pattern. The JSON format is the normal WireMock format which you can read about in the WireMock website.
Currently we support Tomcat, Jetty and Undertow as Spring Boot embedded servers, and Wiremock itself has "native" support for a particular version of Jetty (currently 9.2). To use the native Jetty you need to add the native wiremock dependencies and exclude the Spring Boot container if there is one.