我在测试环境中尝试从-1
获取server.port
属性时返回application.yml
值。
我对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: /
所以这里实际上有两个问题:
@Value
注释注入属性?application.yml
PropertyResolver
来获取所有server.port
个属性?我最终需要的是一种方便的方式来访问经典'中的所有application.yml
属性。测试(即不是Spring集成测试,因为我想在运行时测试应用程序)。我尝试过使用
@ContextConfiguration(classes = TestConfiguration.class, initializers = ConfigFileApplicationContextInitializer.class)
同样,但问题仍然存在。
答案 0 :(得分:1)
如果您没有运行集成测试,SpringApplicationContextLoader
explicitly sets server.port
to -1
。值-1
会禁用嵌入式servlet容器,这是您不使用@WebIntegrationTest
所要求的。
答案 1 :(得分:1)
我遇到了同样的问题,集成测试中的@Value
注释没有用值填充属性(而是占位符$ {..}在那里)。
我现在通过将PropertyPlaceholderAutoConfiguration.class
添加到@SpringApplicationConfiguration
来解决它,即:
@SpringApplicationConfiguration(TestConfiguration.class, PropertyPlaceholderAutoConfiguration.class)
但是我对此并不满意所以我提出了一个如何正确执行此操作的问题: Spring boot integration test with SpringApplicationConfiguration doesn't seem to resolve @Value annotation
答案 2 :(得分:0)
在测试用例中,local.server.port
属性中提供了正在运行的服务器端口:
@Value("${local.server.port}")
private int localServerPort;