springboot~集成测试里的redis

测试不该该访问外部资源

对于单元测试,集成测试里,若是被测试的方法中使用到了redis,你须要去模拟一个单机环境的redis server,由于只有这样,你的测试才是客观的,即不会由于网络和其它因素影响你测试的准确性!java

redis的内嵌版本embedded-redis

它的源码在github上,你们有兴趣能够去看看,很是精简,并且还提供了单机,集群,哨兵多种redis环境,彻底能够知足咱们的测试须要。git

添加依赖

//implementation
 'org.springframework.boot:spring-boot-starter-data-redis',
 
 //testImplementation
 'com.github.kstyrc:embedded-redis:0.6',

添加mock

package com.lind.springOneToOne.mock;

import org.springframework.stereotype.Component;
import redis.embedded.RedisServer;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;

@Component
public class RedisServerMock {

    private RedisServer redisServer;

    /**
     * 构造方法以后执行.
     *
     * @throws IOException
     */
    @PostConstruct
    public void startRedis() throws IOException {
        redisServer = new RedisServer(6379);
        redisServer.start();
    }

    /**
     * 析构方法以后执行.
     */
    @PreDestroy
    public void stopRedis() {
        redisServer.stop();
    }
}

添加测试

public class StringValueTest extends BaseTest {

    @Autowired
    RedisTemplate redisTemplate;

    @Test
    public void setTest() throws Exception {

        redisTemplate.opsForValue().set("ok", "test");
        System.out.println(
                "setTest:" + redisTemplate.opsForValue().get("ok")
        );
    }

}

对于内嵌redis就说到这到,下回有机会说一下内嵌的mongodb,它也是集成测试时不能缺乏的组件!github

相关文章
相关标签/搜索