Search code examples
javaspring-bootgroovyspock

How to change server port in runtime with a spring boot application and spock testing


I am testing a Spring Boot application with Spock, but on one of the test cases I need to mock or stub the calls to the auth server (using oauth 2) so I'm trying to redirect the requests to a dummy server for testing and make the methods return a fixed token. However, i overwrite the port at runtime but i get an error because the dummy server is on a fixed port (read from the application-test.yml), is there a way to change this at runtime to make the server match the random port that the test is running on? this is my setup function:

`def setup() {
        omcService.soapClient = Stub(SOAPClient)
        String url = "http://localhost:${port}"
        nonRetryableExceptionProcessor.omsUrl = url
        omsService.omsUrl = url
        omsService.authUrl = "$url/oauth/token?scope=all"
        omsService = Spy(OmsService)
        producerTemplate.start()
    }

When I debug this test, the properties are changed but when the application performs a GET operation, it points to localhost:4321 always, which is not the random port picked up by Spring


Solution

  • You can inject random port into your test.

    For example using @LocalManagementPort:

        @LocalManagementPort
        int port;
    

    Or directly using @Value:

        @Value("${local.server.port}")
        int port;
    

    But if above doesn't work, then I believe this is your last resort:

        int port = context.embeddedServletContainer.port
    

    Having it injected, you can perform GET to the server on that port.