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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With