I run my Integration Test cases with Spring Boot with the help of my local Redis server on my machine.
But I want an embedded Redis server which is not dependent on any
Another neat way is to use the testcontainers
library which can run any type of application that can in a Docker container and Redis is no exception. What I like best is that it is lightly coupled with the Spring Test ecosystem.
maven's dependency:
org.testcontainers
testcontainers
${testcontainers.version}
simple integration test:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = {"management.port=0"})
@ContextConfiguration(initializers = AbstractIntegrationTest.Initializer.class)
@DirtiesContext
public abstract class AbstractIntegrationTest {
private static int REDIS_PORT = 6379;
@ClassRule
public static GenericContainer redis = new GenericContainer("redis:5-alpine").withExposedPorts(REDIS_PORT);
public static class Initializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext ctx) {
// Spring Boot 1.5.x
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(ctx,
"spring.redis.host=" + redis.getContainerIpAddress(),
"spring.redis.port=" + redis.getMappedPort(REDIS_PORT));
// Spring Boot 2.x.
TestPropertyValues.of(
"spring.redis.host:" + redis.getContainerIpAddress(),
"spring.redis.port:" + redis.getMappedPort(REDIS_PORT))
.applyTo(ctx);
}
}
}
Since Spring Framework 5.2.5 (Spring Boot 2.3.x) you can use the powerful DynamicPropertySource
annotation.
Here is an example:
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public abstract class AbstractIT {
static GenericContainer redisContainer = new GenericContainer("redis:5-alpine").withExposedPorts(6379);
@DynamicPropertySource
static void properties(DynamicPropertyRegistry r) throws IOException {
r.add("spring.redis.host", redisContainer::getContainerIpAddress);
r.add("spring.redis.port", redisContainer::getFirstMappedPort);
}
}