阅读目录
问题描述
application.yml部分配置配置项如下:
server:
port: 8080
domain: localhost
配置项对应的类代码如下:
@Component
@Data
public class SiteConfig {
//域名
@Value("${domain:#{null}}")
private String domain;
//端口号
@Value("${server.port:#{8081}}")
private Integer port;
}
测试类代码如下:
@Slf4j
@SpringBootTest
class SiteConfigTest {
@Resource
private SiteConfig siteConfig;
@Test
void getDomain() {
log.info("siteConfig: {}", siteConfig.getDomain());
assertEquals("localhost", siteConfig.getDomain());
}
@Test
void getPort() {
log.info("Port: {}", siteConfig.getPort());
assertEquals(8080, siteConfig.getPort());
}
}
在测试方法getPort()
中,端口号port获取的值为-1。
原因
测试类启动springboot程序时并没有以配置端口启动服务,所以我们要以配置端口的方式启动服务。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()]);
}
解决
在@SpringBootTest
中添加属性值@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@Slf4j
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class SiteConfigTest {
@Resource
private SiteConfig siteConfig;
@Test
void getDomain() {
log.info("siteConfig: {}", siteConfig.getDomain());
assertEquals("localhost", siteConfig.getDomain());
}
@Test
void getPort() {
log.info("Port: {}", siteConfig.getPort());
assertEquals(8080, siteConfig.getPort());
}
}
参考
https://*.com/questions/46684818/springboot-test-valueserver-port