使用属性server.port = 0运行Spock测试时如何查找Spring Boot容器的端口 [英] How to find port of Spring Boot container when running a spock test using property server.port=0

查看:624
本文介绍了使用属性server.port = 0运行Spock测试时如何查找Spring Boot容器的端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

application.properties中提供此条目:

server.port=0

这会导致Spring Boot选择一个随机可用的端口,并使用spock测试Spring Boot Web应用程序,spock代码如何知道要命中哪个端口?

which causes Spring Boot to chose a random available port, and testing a spring boot web application using spock, how can the spock code know which port to hit?

像这样正常注射:

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

不适用于spock.

推荐答案

您可以使用以下代码找到端口:

You can find the port using this code:

int port = context.embeddedServletContainer.port

对于那些对Java等效语言感兴趣的人是:

Which for those interested in the java equivalent is:

int port = ((TomcatEmbeddedServletContainer)((AnnotationConfigEmbeddedWebApplicationContext)context).getEmbeddedServletContainer()).getPort();

这是一个可以扩展的抽象类,它包装了Spring Boot应用程序的初始化并确定了端口:

Here's an abstract class that you can extends which wraps up this initialization of the spring boot application and determines the port:

abstract class SpringBootSpecification extends Specification {

    @Shared
    @AutoCleanup
    ConfigurableApplicationContext context

    int port = context.embeddedServletContainer.port

    void launch(Class clazz) {
        Future future = Executors.newSingleThreadExecutor().submit(
                new Callable() {
                    @Override
                    public ConfigurableApplicationContext call() throws Exception {
                        return (ConfigurableApplicationContext) SpringApplication.run(clazz)
                    }
                })
        context = future.get(20, TimeUnit.SECONDS);
    }
}

您可以这样使用:

class MySpecification extends SpringBootSpecification {
    void setupSpec() {
        launch(MyLauncher.class)
    }

    String getBody(someParam) {
        ResponseEntity entity = new RestTemplate().getForEntity("http://localhost:${port}/somePath/${someParam}", String.class)
        return entity.body;
    }
}

这篇关于使用属性server.port = 0运行Spock测试时如何查找Spring Boot容器的端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆