在测试上下文中尝试从 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/