testing - 无法在 @SpringApplicationConfiguration 注释测试中从 application.yml 获取 ${server.port}

标签 testing spring-boot

在测试上下文中尝试从 application.yml 获取 server.port 属性时,我得到返回的 -1 值。

我对 Spring-bot 应用进行黑盒测试。 这是一个测试用例:

@SpringApplicationConfiguration(TestConfiguration.class)
public class StartupTest extends AbstractTestNGSpringContextTests implements EnvironmentAware {

    private static Logger logger = LoggerFactory.getLogger(StartupTest.class);

    @Value("${server.port}")
    private String port;

    @Value("${project.name}")
    private String name;

    private RelaxedPropertyResolver propertyResolver;

    @Override
    public void setEnvironment(Environment environment) {
        this.propertyResolver = new RelaxedPropertyResolver(environment);
    }

    @Test
    public void isAppUpAndRunning() {
        logger.debug("port: " + port);
        logger.debug("name: " + name);
        logger.debug("value for project.name: " + propertyResolver.getProperty("project.name"));
        logger.debug("value for server.port: " + propertyResolver.getProperty("server.port"));
        logger.debug("value for server.servlet-path: " + propertyResolver.getProperty("server.servlet-path"));
    }
}

注意:TestConfiguration.class 只包含 @Configuration

输出:

[DEBUG] com.project.StartupTest - Running with Spring Boot v1.3.3.RELEASE, Spring v4.2.5.RELEASE
[INFO] com.project.StartupTest - The following profiles are active: test
[INFO] com.project.StartupTest - Started StartupTest in 4.698 seconds (JVM running for 7.761)
[DEBUG] com.project.StartupTest - port: ${server.port}
[DEBUG] com.project.StartupTest - name: ${project.name}
[DEBUG] com.project.StartupTest - value for project.name: MyProject
[DEBUG] com.project.StartupTest - value for server.port: -1
[DEBUG] com.project.StartupTest - value for server.servlet-path: /

所以这里实际上有 2 个问题:

  • 为什么我无法获得使用 @Value 注解注入(inject)的属性?
  • 为什么我可以使用 PropertyResolver 而不是 server.port 获取所有 application.yml 属性?

我最终需要的是一种方便的方式来访问“经典”测试中的所有 application.yml 属性(即,不是 Spring 集成测试,因为我想按原样测试应用程序运行)。我试过使用

@ContextConfiguration(classes = TestConfiguration.class, initializers = ConfigFileApplicationContextInitializer.class)

同样如此,但问题依旧。

最佳答案

如果您没有运行集成测试,SpringApplicationContextLoader explicitly sets server.port to -1 . -1 的值禁用嵌入式 servlet 容器,这是您通过不使用 @WebIntegrationTest 所要求的。

关于testing - 无法在 @SpringApplicationConfiguration 注释测试中从 application.yml 获取 ${server.port},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36571216/

相关文章:

android - 仅使用一部手机和模拟器即可进行大众测试

java - 为什么 spring boot webflow 验证失败?

testing - 有没有这样的测试工具

selenium - 如何不连续重复依赖于该背景场景的 Cucumber 功能的背景场景

java - Spring Boot Actuator/env 端点以 XML 形式返回数据 - 为什么?

Java Spring Boot - 如何像在 PHP Laravel 中一样为数据库播种

spring-boot - 如何从 openssl 生成的 key 生成 X.509 证书

java - SpringBoot 和 JUnit - 测试服务类 - 无法加载应用程序上下文

javascript - ExecuteScript 不执行 html 中描述的函数,这些函数在页面加载后运行

vue.js - 无法窥探原始值;给定的未定义。 Vue JS、Jest、实用程序