Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set property with wiremock random port in spring boot test

I have a Spring Boot test that uses wiremock to mock an external service. In order to avoid conflicts with parallel builds I don't want to set a fixed port number for wiremock and would like to rely on its dynamic port configuration.

The application uses a property (external.baseUrl) set in the application.yml (under src/test/resources). However I didn't find a way to programmatically override that. I've tried something like this:

    WireMockServer wireMockServer = new WireMockServer();
    wireMockServer.start();
    WireMock mockClient = new WireMock("localhost", wireMockServer.port());
    System.setProperty("external.baseUrl", "http://localhost:" + wireMockServer.port());

but it didn't work and the value in application.yml was used instead. All other solutions that I've looked at override the property with a static value (for example in some annotation), but I don't know the value of the wiremock port until the test is run.

Clarification:

Both spring boot and wiremock run on random ports. That's fine and I know how to get the value of both ports. However wiremock is supposed to mock an external service and I need to tell my application how to reach it. I do this with the external.baseUrl property. The value I want to set in my test depends of course on the wiremock port number. My problem is simply how to programmatically set a property in a spring boot test.

like image 848
Nicola Ambrosetti Avatar asked Feb 09 '18 14:02

Nicola Ambrosetti


2 Answers

Consider using Spring Cloud Contract Wiremock

There is already a JUnit Rule builder which allows to specify ${wiremock.port} to set random port in property/yaml files

Or you can use WireMockRestServiceServer to bind WireMock to your RestTemplate so you don't even need to override URLs in your tests.

like image 150
Dagon Avatar answered Oct 11 '22 11:10

Dagon


Use property substitution in your application.properties:

external.baseUrl=http://exampleUrl:${wiremock.server.port}

This requires the wiremock.server.port property to be set before the SpringBootTest is initialised, which can be achieved by adding the @AutoConfigureWireMock annotation to your test class.

like image 8
user3302637 Avatar answered Oct 11 '22 10:10

user3302637