1. 程式人生 > >springboot~整合測試裡的redis

springboot~整合測試裡的redis

測試不應該訪問外部資源

對於單元測試,整合測試裡,如果被測試的方法中使用到了redis,你需要去模擬一個單機環境的redis server,因為只有這樣,你的測試才是客觀的,即不會因為網路和其它因素影響你測試的準確性!

redis的內嵌版本embedded-redis

它的原始碼在github上,大家有興趣可以去看看,非常精簡,而且還提供了單機,叢集,哨兵多種redis環境,完全可以滿足我們的測試需要。

新增依賴

//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,它也是整合測試時不能缺少的元件!