可靠的库用于Spring启动redis集成测试

时间:2018-05-21 20:47:02

标签: spring-boot redis integration-testing

这更像是一个工具的问题 - 谷歌搜索我还没有真正的运气。

所以基本上我有一个标准的spring boot应用程序 - 我有一个单元测试redis缓存配置。我想要做的是运行应用程序上下文自动装配一些弹簧配置并在可能的情况下对嵌入式redis缓存进行测试。

我最近来的就是https://github.com/kstyrc/embedded-redis

问题在于缺乏强大的日志记录使其难以运行 - 它在本地工作,但是当我推动它时,Unix服务器构建机器,它失败并且不知道为什么。

如果有人知道如何以这种方式运行集成测试 - 那就太好了。

感谢,

的Stefan

1 个答案:

答案 0 :(得分:2)

我正在使用embedded-redis与Redisson Java Client进行集成测试。 这是我的依赖

compile group: 'org.redisson', name: 'redisson', version: '3.6.5'
testCompile group: 'it.ozimov', name: 'embedded-redis', version: '0.7.2'

在上课之前启动嵌入式Redis服务器,并在下课后停止它。

Redis属性:

spring.redis.host=localhost
spring.redis.port=6379

示例集成测试。

import java.util.concurrent.TimeUnit;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.redisson.api.RMap;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;


import redis.embedded.RedisServer;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public class RedisTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisTest.class);

    private static RedisServer REDISSERVER = new RedisServer(6379);

    @LocalServerPort
    private int port;

    @Autowired
    private RedissonClient redissonClient;

    @BeforeClass
    public static final void before() {
        REDISSERVER.start();
    }

    @AfterClass
    public static  final void after() { 
        REDISSERVER.stop();
    }

    @Test
    public void testRedis() throws InterruptedException {
        //map
        RMap<String, String> map = redissonClient.getMap("user");
        map.put("name", "Redis Server");
        Assert.assertTrue(map.get("name").equals("Redis Server"));

        //mapcache
        RMapCache<String, String> mapCache = redissonClient.getMapCache("tempUser");
        mapCache.put("name", "Redis Server", 5, TimeUnit.SECONDS);
        Assert.assertTrue(mapCache.get("name").equals("Redis Server"));
        Thread.sleep(7000); //wait for 7 sec.
        Assert.assertTrue(mapCache.get("name") == null);
    }
}