如何使用 spring 引导应用程序和 spock 测试在运行时更改服务器端口

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

我正在使用 Spock 测试一个 Spring 引导应用程序,但是在其中一个测试用例中,我需要模拟或存根对 auth 服务器的调用(使用 oauth 2),所以我正在尝试重定向对虚拟服务器的请求进行测试,并使方法 return 成为固定令牌。但是,我在运行时覆盖了端口,但出现错误,因为虚拟服务器位于固定端口(从 application-test.yml 读取),有没有办法在运行时更改它以使服务器匹配随机端口测试 运行 开始了吗? 这是我的 setup 函数:

`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()
    }

当我调试这个测试时,属性被改变了,但是当应用程序执行GET操作时,它总是指向localhost:4321,这不是Spring[=选择的随机端口15=]

您可以将随机端口注入到您的测试中。

例如使用@LocalManagementPort:

    @LocalManagementPort
    int port;

或者直接使用@Value:

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

但如果上述方法不起作用,那么我相信这是你最后的选择:

    int port = context.embeddedServletContainer.port

注入后,您可以在该端口上对服务器执行 GET。