鉴于此条目application.properties
:
server.port=0
这会导致 Spring Boot 选择一个随机可用端口,并使用 spock 测试 Spring Boot Web 应用程序,spock 代码如何知道要访问哪个端口?
正常注入是这样的:
@Value("${local.server.port}")
int port;
不适用于斯波克。
您可以使用以下代码找到端口:
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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)