springboot~集成測試里的redis
測試不應該訪問外部資源
對(dui)于單元測試(shi)(shi),集成測試(shi)(shi)里,如果(guo)被測試(shi)(shi)的(de)(de)方法(fa)中使用到了redis,你(ni)需(xu)要去(qu)模擬一(yi)個(ge)單機環境的(de)(de)redis server,因為只有(you)這樣(yang),你(ni)的(de)(de)測試(shi)(shi)才是客觀的(de)(de),即不(bu)會(hui)因為網(wang)絡和其它因素影響你(ni)測試(shi)(shi)的(de)(de)準確性(xing)!
redis的內嵌版本embedded-redis
它的(de)源碼在github上,大家有興趣(qu)可以(yi)去看看,非常(chang)精簡,而且還提供(gong)了單(dan)機,集(ji)群,哨兵多種redis環境,完全可以(yi)滿足我們的(de)測試需(xu)要。
添加依賴
//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")
);
}
}
對于(yu)內嵌redis就(jiu)說到這到,下(xia)回有機會說一下(xia)內嵌的(de)mongodb,它(ta)也(ye)是集成測試時不能缺(que)少(shao)的(de)組(zu)件!