我正在寻找有关在集成测试中将management.port
属性设置为时如何获取分配给为执行器端点提供服务的嵌入式 tomcat 的端口的建议。0
我使用具有以下application.yml
配置的 Spring Boot 1.3.2:
server.port: 8080
server.contextPath: /my-app-context-path
management.port: 8081
management.context-path: /manage
...
然后我的集成测试用 注释@WebIntegrationTest
,将上面显示的端口设置为0
@WebIntegrationTest({ "server.port=0", "management.port=0" })
在进行完整集成测试时,应使用以下实用程序类来访问应用程序配置:
@Component
@Profile("testing")
class TestserverInfo {
@Value( '${server.contextPath:}' )
private String contextPath;
@Autowired
private EmbeddedWebApplicationContext server;
@Autowired
private ManagementServerProperties managementServerProperties
public String getBasePath() {
final int serverPort = server.embeddedServletContainer.port
return "http://localhost:${serverPort}${contextPath}"
}
public String getManagementPath() {
// The following wont work here:
// server.embeddedServletContainer.port -> regular server port
// management.port -> is zero just as server.port as i want random ports
final int managementPort = // how can i get this one ?
final String managementPath = managementServerProperties.getContextPath()
return "http://localhost:${managementPort}${managementPath}"
}
}
我已经知道标准端口可以通过使用来获得,local.server.port
并且对于名为local.management.port
. 但这似乎有不同的含义。
编辑:官方文档没有提到这样做的方法:(http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-discover-the-http-port-at -运行时)
目前是否有任何未记录的方式来获得该管理端口?
解决方案编辑:
当我使用 Spock-Framework 和 Spock-Spring 来测试我的 spring-boot 应用程序时,我必须使用以下方法初始化应用程序:
@ContextConfiguration(loader = SpringApplicationContextLoader.class, classes = MyApplication.class)
不知何故,Spock-Spring 或测试初始化似乎会影响@Value
注释的评估,从而@Value("${local.management.port}")
导致
java.lang.IllegalArgumentException: Could not resolve placeholder 'local.management.port' in string value "${local.management.port}"
使用您的解决方案,我知道该属性存在,因此我只是直接使用弹簧Environment
在测试运行时检索属性值:
@Autowired
ManagementServerProperties managementServerProperties
@Autowired
Environment environment
public String getManagementPath() {
final int managementPort = environment.getProperty('local.management.port', Integer.class)
final String managementPath = managementServerProperties.getContextPath()
return "http://localhost:${managementPort}${managementPath}"
}