Mock redis template

lahirumw picture lahirumw · Apr 9, 2017 · Viewed 12.5k times · Source

I am facing a issue in mock redis template. Can any one help me to write unit test for below class.

@Repository
public class CasheRepo {

    @Autowired
    private RedisTemplate<String, Object> template;

    public Object getObject(final String key) {
    return template.opsForValue().get(key);
    }
}

And below is unit test class. But it is not working. It shows null point exceptions

@RunWith(MockitoJUnitRunner.class)
public class CashRepoTest {
    @InjectMocks
    private CasheRepo casheRepo = new CasheRepo();

    private @Mock RedisConnection redisConnectionMock;
    private @Mock RedisConnectionFactory redisConnectionFactoryMock;

    private RedisTemplate redisTemplate;

    @Before
    public void setUp() {   Mockito.when(redisConnectionFactoryMock.getConnection()).thenReturn(redisConnectionMock);   
    redisTemplate = new RedisTemplate();
    redisTemplate.setConnectionFactory(redisConnectionFactoryMock);
    redisTemplate.afterPropertiesSet();
    }

    @Test
    public void getObjectTest() {
    Mockito.doNothing().when(redisTemplate).opsForValue().set("spring", "data");
    redisTemplate.afterPropertiesSet();  
    System.out.println(redisTemplate.opsForValue().get("spring"));   
    }    
}

Answer

张泽光 picture 张泽光 · Feb 1, 2018

you can mock redisTemplate like this:

@Mock
RedisTemplate<String, String> redisTemplate;

@Mock
private ValueOperations valueOperations;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    Mockito.when(redisTemplate.opsForValue()).thenReturn(valueOperations);
    Mockito.doNothing().when(valueOperations).set(anyString(), anyString());
}