At my company, we're building an API on top of other ones. So when the front end calls one of our endpoints, it calls other endpoints (that we haven't developed), process the result and return it our own response suitable to our front end code.Pretty clear? Now, the thing is that we want to mock these underlying systems since we don't have control over them. Sometimes they're down (u know legacy stuff). So, Mocking is the solution. However, since it's just a bunch of API clients that we have all around our project, we wanted to consolidate all of these by actually creating a service (a Spring Boot Application) configured with all the requests matching rules that you spin up and test against it. In other words, our actual controllers tests won't be aware of any of these because it's happening at a low level.
So I chose WireMock as a solution. Here's how I did it:
I created a new project called wiremock-service with the main class WiremockServiceApplication.
@SpringBootApplication
public class WiremockServiceApplication {
public static void main(String[] args) {
SpringApplication.run(WiremockServiceApplication.class, args);
}
}
I then created another component called WireMockStubsConfig.
@Component
public class WireMockStubsConfig {
WireMockServer wireMockServer;
@PostConstruct
public void initWireMockServer(){
wireMockServer = new WireMockServer(wireMockConfig().port(8089));
wireMockServer.start();
}
@PostConstruct
public void stubs() {
WireMock.configureFor("localhost", 8089);
givenThat(get(urlEqualTo("/whatever"))
.willReturn(aResponse()
.withStatus(200)
.withBody("Content!!")
.withHeader("Content-Type", "application/json")
.withHeader("Cache-Control", "no-cache")));
givenThat(get(urlEqualTo("/mocked-soap-service.wsdl"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBodyFile("/ws/SayHello.xml")));
}
}
So my code is working but what I'm hoping to get through your answers guys is whether there's a "better way to do"?! Also, in the second "givenThat", I'm specifying a bodyFile that it should be under src/test/resource folder and not the src/main/resource one. My last concern is that I'm having two launched servers. The first one which is WireMock at 8089 and also the second one which is the Spring Boot Application at 8080.
Thanks
Aucun commentaire:
Enregistrer un commentaire