對於單元測試,集成測試裏,若是被測試的方法中使用到了redis,你須要去模擬一個單機環境的redis server,由於只有這樣,你的測試纔是客觀的,即不會由於網絡和其它因素影響你測試的準確性!java
它的源碼在github上,你們有興趣能夠去看看,很是精簡,並且還提供了單機,集羣,哨兵多種redis環境,徹底能夠知足咱們的測試須要。git
//implementation 'org.springframework.boot:spring-boot-starter-data-redis', //testImplementation 'com.github.kstyrc:embedded-redis:0.6',
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