我正在微服务环境中编写集成测试。我想在运行 JUnit 测试类时完全初始化 Spring Boot 应用程序上下文。在正常情况下我可以很容易地做到这一点,但在这种情况下我需要从 Git 存储库加载远程配置(我使用的是 spring-cloud-config)。在正常启动条件下,此 Spring Boot 应用程序确实成功从 Git 存储库加载配置。我只是想在测试阶段复制相同的上下文初始化。这是我编写测试类的方式:
@RunWith(SpringRunner.class)
@SpringBootTest(properties={"ENV=local","spring.cloud.config.enabled=true","spring.cloud.config.uri=http://config.server.com/config","ENCRYPT_KEY=secret"})
@ContextConfiguration(classes ={MyAppConfig.class,MyDBConfig.class})
@PropertySource({"classpath:spring-cloud-config.properties"})
public class MyIntegrationTest {
@Test
public void testFindUsersForCorp() {
System.out.println("Test is running ");
}
}
spring-cloud-config.properties:
spring.profiles.active=${ENV}
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration
spring.cloud.consul.host=${CONSUL.HOST:localhost}
spring.cloud.consul.port=${CONSUL.PORT:8500}
spring.cloud.consul.discovery.healthCheckPath=/custom/health
spring.cloud.consul.discovery.healthCheckInterval=30s
spring.cloud.config.uri=${CONFIG.SERVER.URI:http://config.server:80/config}
spring.cloud.config.username=user
spring.cloud.config.password=${PASSWORD}
在 Spring 上下文初始化期间记录输出:
main WARN: Could not locate PropertySource: I/O error on GET request for "http://localhost:8888/userdata-service/default": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
main WARN: Cannot enhance @Configuration bean definition 'refreshScope' since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
main ERROR:
***************************
APPLICATION FAILED TO START
***************************
Description:
Cannot determine embedded database driver class for database type NONE
[OMITTED]
如上所示,启动失败,因为没有定义持久层的驱动程序类。由于相关配置在Git中,此错误表明未获取远程配置。
我感谢任何人可以提供的帮助。如果需要,我将用更多信息更新此问题。
最佳答案
Spring Cloud Config 客户端应该在 bootstrap 阶段初始化,因此您应该将相应的属性从 spring-cloud-config.properties 移动到 bootstrap.properties 请参阅https://cloud.spring.io/spring-cloud-config/multi/multi__spring_cloud_config_client.html#config-first-bootstrap
关于java - 使用 JUnit Test 的远程配置启动 Spring Boot 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42101954/