gpt4 book ai didi

testing - 使用属性 server.port=0 运行 spock 测试时如何查找 Spring Boot 容器的端口

转载 作者:行者123 更新时间:2023-11-28 19:45:26 24 4
gpt4 key购买 nike

给定 application.properties 中的条目:

server.port=0

这导致 Spring Boot 选择随机可用端口,并使用 spock 测试 spring boot web 应用程序,spock 代码如何知道要访问哪个端口?

像这样的正常注入(inject):

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

不适用于 spock。

最佳答案

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

int port = context.embeddedServletContainer.port

对于那些对 java 等价物感兴趣的人来说是:

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

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

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;
}
}

关于testing - 使用属性 server.port=0 运行 spock 测试时如何查找 Spring Boot 容器的端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24643483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com