我正在微服务环境中编写集成测试。我想在运行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]
如上所示,启动失败,因为没有定义我的persistance层的驱动程序类。由于相关配置在Git中,因此该错误表示未提取远程配置。
我感谢任何人都可以提供帮助。如果需要,我会用更多信息更新这个问题。
答案 0 :(得分:0)
Spring Cloud Config客户端应在引导阶段初始化,因此您应将相应的属性从 spring-cloud-config.properties 移至 bootstrap.properties 参见https://cloud.spring.io/spring-cloud-config/multi/multi__spring_cloud_config_client.html#config-first-bootstrap