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"));   
    }    
}
                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());
}
                        For those who want to do the same with HashOperations get() and put()
    @Mock
    RedisTemplate<String, String> redisTemplate;
    
    @Mock
    private HashOperations hashOperations;
     
    @Test
    void getFromCache() {
         Mockito.when(redisTemplate.opsForHash()).thenReturn(hashOperations);
         when(hashOperations.get("test-key", "test-hash-key")).thenReturn("value123");
         RedisCacheServiceImpl cacheService = new RedisCacheServiceImpl(redisTemplate);
         assertEquals("value123", cacheService.getFromCache("test-key", "test-hash-key"));
    }
Hope it helps you ;)
While I faced with a similar task, I've made a tool(annotation) based on mock-jedis to solve it in easy way. You could read about it here: https://github.com/incu6us/redis-mock-template or just add a dependency to your project:
<dependency>
  <groupId>com.github.incu6us.redis</groupId>
  <artifactId>redis-mock-template</artifactId>
  <version>0.0.1</version>
</dependency>
                        You are creating redisTemplate via constructor, and it was not got by DI. Try to use @Spy annotation:
@Spy
private RedisTemplate redisTemplate = new RedisTemplate();
It will allow DI to inject your instance of RedisTemplate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With