【发布时间】:2018-11-24 04:37:00
【问题描述】:
我正在我的 Spring Boot 应用程序中进行集成测试。该应用需要使用 Redis。
在开发阶段,我有一个应用程序连接到的 Redis 本地容器。
对于集成测试,我使用的是testcontainers,我也关注了他们的example of how to use a Redis container。
在某些时候,我明白只有在开发容器启动并运行时才能正确运行测试。如果它关闭,则集成测试正在下降,因为它们无法到达 Redis。
所以集成测试类看起来像这样:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SharkApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(locations = "classpath:application-integrationtests.yml")
@AutoConfigureMockMvc
public class SharkIntegrationTest {
static GenericContainer redis = new GenericContainer("redis:3.0.6")
.withExposedPorts(6379);
@BeforeClass
public static void before(){
redis.start();
}
@AfterClass
public static void after(){
redis.stop();
}
...
运行测试时,我可以在日志中看到:
14:36:24.372 [main] DEBUG ???? [redis:3.0.6] - Starting container: redis:3.0.6
14:36:24.372 [main] DEBUG ???? [redis:3.0.6] - Trying to start container:
redis:3.0.6
14:36:24.373 [main] DEBUG ???? [redis:3.0.6] - Trying to start container:
redis:3.0.6 (attempt 1/1)
14:36:24.373 [main] DEBUG ???? [redis:3.0.6] - Starting container: redis:3.0.6
14:36:24.373 [main] INFO ???? [redis:3.0.6] - Creating container for image:
redis:3.0.6
...
14:36:25.282 [main] INFO ???? [redis:3.0.6] - Container redis:3.0.6 started
但随后应用程序失败,因为它无法访问 Redis:
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused: connect
在某些时候,我尝试更改容器应该启动的端口。从 6379 到 16379(在代码和 yml 文件中都更改了),但随后测试进入无限循环并打印到屏幕:
14:41:57.258 [ducttape-0] DEBUG org.testcontainers.containers.ExecInContainerPattern - /amazing_beaver: Running "exec" command: /bin/bash -c </dev/tcp/localhost/16379 && echo
【问题讨论】:
-
您可以使用@DynamicPropertySource 动态(DynamicPropertyRegistry 注册表)添加主机/端口。
标签: java redis integration-testing testcontainers