測試不應該訪問外部資源
對于單元測試,集成測試里,如果被測試的方法中使用到了redis,你需要去模擬一個單機環境的redis server,因為只有這樣,你的測試才是客觀的,即不會因為網絡和其它因素影響你測試的準確性!
redis的內嵌版本embedded-redis
它的源碼在github上,大家有興趣可以去看看,非常精簡,而且還提供了單機,集群,哨兵多種redis環境,完全可以滿足我們的測試需要。
添加依賴
1
2
3
4
|
//implementation 'org.springframework.boot:spring-boot-starter-data-redis' , //testimplementation 'com.github.kstyrc:embedded-redis:0.6' , |
添加mock
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
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(); } } |
添加測試
1
2
3
4
5
6
7
8
9
10
11
|
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,它也是集成測試時不能缺少的組件!
總結
以上所述是小編給大家介紹的springboot集成測試里的redis,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/lori/p/9946153.html