我在模拟Redis模板中遇到问题。
谁能帮我为下课写单元测试。

@Repository
public class CasheRepo {

    @Autowired
    private RedisTemplate<String, Object> template;

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

下面是单元测试类(class)。但这是行不通的。它显示空点异常
@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"));
    }
}

最佳答案

您可以像这样模拟redisTemplate:

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

10-07 22:54