我正在我的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