Mock redis template

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

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"));        }     } 

回答1:

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.



回答2:

you can mock redisTemplate like this:

@Mock RedisTemplate 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()); } 


文章来源: Mock redis template
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!