@TestConfiguration for Embedded Redis,所有测试类均使用同一Redis Server

问题描述

我使用Embedded Redis进行集成测试。我根据以下文章使用Redis进行了测试:https://www.baeldung.com/spring-embedded-redis

问题是,如果我想将@TestConfiguration与多个测试类一起使用,则会收到错误,因为未调用@PreDestroy。嵌入式Redis每次都是新创建的,并且不会在测试类之间共享。因此,每次尝试在同一端口上创建新的Redis Sserver时,都会导致以下错误

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRedisConfiguration': 
Invocation of init method Failed; @R_404_6431@ted exception is java.lang.RuntimeException: 
Can't start redis server. Check logs for details.

当我将@DirtiesContext添加到所有测试类时,出现以下错误

java.lang.IllegalStateException: org.springframework.web.context.support.GenericWebApplicationContext@255e5e2e has been closed already

是否可以对我的所有测试类使用相同的嵌入式Redis

解决方法

您可以使用带有@BeforeClass批注的方法来初始化EmbeddedRedis。这将限制整个测试类的redis缓存构造一次。