server.port 在单元测试中,调用的类或者方法这个地方获取到的端口号就会变成-1

时间:2023-03-08 23:11:28
server.port 在单元测试中,调用的类或者方法这个地方获取到的端口号就会变成-1
@Value("${server.port}")
本文链接:https://blog.****.net/weixin_38342534/article/details/88698582 首先 @Value("${server.port}") 获取端口号没有任何问题,那么问题出在那呢,出在单元测试中!!! 你在单元测试中,调用的类或者方法这个地方获取到的端口号就会变成-1。 解决办法:在后面加上下属性 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) 原理: org.springframework.boot.test.context.SpringBootContextLoader#getInlinedProperties
protected String[] getInlinedProperties(MergedContextConfiguration config) {
ArrayList<String> properties = new ArrayList<String>();
// JMX bean names will * if the same bean is used in multiple contexts
disableJmx(properties);
properties.addAll(Arrays.asList(config.getPropertySourceProperties()));
if (!isEmbeddedWebEnvironment(config) && !hasCustomServerPort(properties)) {
properties.add("server.port=-1");
}
return properties.toArray(new String[properties.size()]);
}
感谢某些大佬,大家可以参照:https://*.com/questions/46684818/springboot-test-valueserver-port