skip to Main Content

I use a Embedded Redis for integration testing. I set up my tests with Redis according to following article: https://www.baeldung.com/spring-embedded-redis.

The problem is, if I want to use the @TestConfiguration with several test classes, I get errors because @PreDestroy is not called. The Embedded Redis is created new each time and is not shared between the test classes. It is therefore tried every time to create a new Redis Sserver on the same port, which leads to the following error:

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

When I add the @DirtiesContext to all test classes I get following error:

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

Is there a way to use the same Embedded Redis for all my test classes?

2

Answers


  1. You can initialize the EmbeddedRedis in a method with @BeforeClass annotation. This will restrict your redis cache construction for the entire Test Class once.

    Login or Signup to reply.
  2. resolved the same issue by adding custom annotation and annotating each test class with it. here is an example in kotlin:

    @TestConfiguration
    class IntegrationRedisConfiguration(
        @Value("${spring.redis.port}") redisPort: Int
    ) {
        private val redisServer: RedisServer = RedisServer(redisPort)
    
        @PostConstruct
        fun postConstruct() = redisServer.start()
    
        @PreDestroy
        fun preDestroy() = redisServer.stop()
    }
    
    @SpringBootTest(
        classes = [IntegrationRedisConfiguration::class]
    )
    annotation class IntegrationTest
    
    @IntegrationTest
    class Service1Spec : FunSpec() { ... }
    
    @IntegrationTest
    class Service2Spec : FunSpec() { ... }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search