mockito+testng Mock Redis

liguangix 2016-11-17

package yy.xx.redis;

import org.apache.log4j.Logger;

import org.springframework.stereotype.Repository;

import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisPool;

@Repository

public class RedisDAO {

  private static final Logger logger = Logger.getLogger(RedisDAO.class);

  

  private JedisPool jedisPool;

  

  public JedisPool getJedisPool() {

    return jedisPool;

  }

  public void setJedisPool(JedisPool jedisPool) {

    this.jedisPool = jedisPool;

  }

  public Jedis getClient() {

    Jedis redisClient = jedisPool.getResource();

    if(redisClient == null){

      return redisClient;

    }

    if (!redisClient.isConnected()) {

      redisClient.connect();

      logger.debug("redisClient is on connect");

    }

    return redisClient;

  }

  public void closeClient(Jedis client) {

    if (client != null)

      jedisPool.returnResource(client);

    logger.debug("redisClient is return resource");

  }

}

package yy.xx.redis;

import org.mockito.InjectMocks;

import org.mockito.Mock;

import org.mockito.Mockito;

import org.mockito.MockitoAnnotations;

import org.testng.Assert;

import org.testng.annotations.Test;

import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisPool;

public class RedisDAOTest {

  @InjectMocks//有实际方法调用时用,比如set了想看GET

  private RedisDAO dao;

  

  private final Jedis redisClient = Mockito.mock(Jedis.class); 

  private final JedisPool jedisPool = Mockito.mock(JedisPool.class); 

  

  @Test

  public void test() {

    MockitoAnnotations.initMocks(this);

    Assert.assertNotNull(dao);

    dao.setJedisPool(jedisPool);

    Assert.assertNotNull(dao.getJedisPool());

    Mockito.when(dao.getClient()).thenReturn(redisClient);

    Assert.assertNotNull(dao.getClient());

    

    dao.closeClient(redisClient);  

  }

}

相关推荐

morexyoung / 0评论 2019-12-01