Java UT用例实践记录
最近重构过程中在补充以前代码的用例,正好把UT用例的实践经验记录下来。
Redis打桩
很多程序都会使用redis管理缓存,UT用例需要解除对远端redis server的依赖,实现用例本地运行。上网找了一些资料加自己实践,推荐使用Embedded RedisServer。
maven
<dependency>
<groupId>it.ozimov</groupId>
<artifactId>embedded-redis</artifactId>
<version>0.7.2</version>
<scope>test</scope>
</dependency>
连接redis
JedisPool pool = new JedisPool("localhost", 6379);
Jedis jedis = pool.getResource();
然后就可以像连接标准redis server一样,使用jedis的各种命令来访问了。
jedis注入到代码
至于怎么将redis连接注入到代码,不同的代码差异较大,需要具体研究。常见的实现是通过静态方法拿到redis连接,所以我通过JMockit的能力来注入。
private void mock() {
new Expectations(RedisUtil.class) {
{
Deencapsulation