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 server and can run on any environment, like the H2 in-memory database. How can I do it?
@RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @IntegrationTest("server.port:0") @SpringApplicationConfiguration(classes = Application.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class MasterIntegrationTest { }
Redis is driven by a keystore-based data structure to persist data and can be used as a database, cache, message broker, etc. We'll be able to use the common patterns of Spring Data (templates, etc.) while also having the traditional simplicity of all Spring Data projects.
You can use an embedded Redis like https://github.com/kstyrc/embedded-redis
Adjust the properties for your integration test to point to your embedded redis, for example :
spring: redis: host: localhost port: 6379
Instanciate the embedded redis server in a component that is defined in your tests only :
@Component public class EmbededRedis { @Value("${spring.redis.port}") private int redisPort; private RedisServer redisServer; @PostConstruct public void startRedis() throws IOException { redisServer = new RedisServer(redisPort); redisServer.start(); } @PreDestroy public void stopRedis() { redisServer.stop(); } }
You can use ozimov/embedded-redis as a Maven(-test)-dependency (this is the successor of kstyrc/embedded-redis).
Add the dependency to your pom.xml
<dependencies> ... <dependency> <groupId>it.ozimov</groupId> <artifactId>embedded-redis</artifactId> <version>0.7.1</version> <scope>test</scope> </dependency>
Adjust your application properties for your integration test
spring.redis.host=localhost spring.redis.port=6379
Use the embedded redis server in a test configuration
@TestConfiguration public static class EmbededRedisTestConfiguration { private final redis.embedded.RedisServer redisServer; public EmbededRedisTestConfiguration(@Value("${spring.redis.port}") final int redisPort) throws IOException { this.redisServer = new redis.embedded.RedisServer(redisPort); } @PostConstruct public void startRedis() { this.redisServer.start(); } @PreDestroy public void stopRedis() { this.redisServer.stop(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With