Skip to content
Advertisement

RedisTemplate mock is only working in the test class

Class A{
  
@Autowired
private RedisTemplate<String, Object> redisTemplate;

    private String readFromCache(String bucket, String key) {
            Object object = redisTemplate.opsForHash().get(bucketName, key);
            System.out.println("----" + redisTemplate.opsForHash().get("1", "1"));
            String returnValue = "";
            if (Objects.nonNull(object))
                returnValue = object.toString();
            return returnValue;
        }
    }

Class B

    Class B extends A{
       
    someMethod(){
       readFromCache(bucketName , key);
      }
    }

Now when I am writing the test for method in class B i.e. someMethod().

     @RunWith(SpringJUnit4ClassRunner.class)
            @SpringBootTest
            @ActiveProfiles("test")
            ClassBTest(){

            @InjectMocks
Class B
            
            @Mock
            @Qualifier("redisTemplate")
            RedisTemplate<String, Object> redisTemplate;
            
            @Mock
            HashOperations<String, Object, Object> hashOpertaions;
              
    @Test
               someMethodTest(){
             Mockito.when(redisTemplate.opsForHash()).thenReturn(hashOpertaions);
                Mockito.doReturn("aa").when(hashOpertaions).get(Mockito.any(), Mockito.any());
    someMethod();
    //assertions
               
        }
            }

I have observed that the redis template mock is generating in test class but not in Class A and class B

Inside ClassBTest enter image description here

Inside class B enter image description here

Why is the mock not working in class B and A ?

Advertisement

Answer

My issue is resolved now. This works for me

@MockBean
    @Qualifier("redisTemplate")
    RedisTemplate<String, Object> redisTemplate;

    @MockBean
    HashOperations<String, Object, Object> hashOpertaions;

    @MockBean
    RedisKeyValueAdapter redisKeyValueAdapter;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement