解决在springboot测试中@value 获取server.port=-1情况

阅读目录

问题描述

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

上一篇:SpringBootTest-初始化上下文之前执行方法


下一篇:SpringBoot2.X @SpringBootTest单元测试