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 ?

2 answers

  • answered 2021-06-10 12:17 deepakchethan

    You are not injecting the mocks into the service that you are testing. It can be done with @InjectMocks before the classes that you want to test. You can try:

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest
    @ActiveProfiles("test")
    ClassBTest(){
    
        @Mock
        RedisTemplate<String, Object> redisTemplate;
        
        @Mock
        HashOperations<String, Object, Object> hashOpertaions;
    
        @InjectMocks
        B objectOfB;  // this would inject the created mocks into the class
          
        @Test
        someMethodTest(){
            Mockito.when(redisTemplate.opsForHash()).thenReturn(hashOpertaions);
            Mockito.doReturn("aa").when(hashOpertaions).get(Mockito.any(), Mockito.any());
            objectOfB.someMethod();
            //assertions
           
       }
    }
    

  • answered 2021-06-10 15:49 HMT

    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;