測試不應該訪問外部資源
對於單元測試,集成測試里,如果被測試的方法中使用到了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,它也是集成測試時不能缺少的組件!