在我的控制器中,我有如下代码。 RedisTemplate stringRedisTemplate
def accessRedis()
{
val = stringRedisTemplate.opsForValue().get('Key')
}
在我的控制器测试中,我打算注入一个模拟的RedisTemplate,它返回一个模拟的ValueOperations。我的代码:
def template = mockFor(RedisTemplate)
def val = mockFor(org.springframework.data.redis.core.ValueOperations)
val.demand.get {p-> println "$p"}
template.demand.opsForValue {
return val.createMock()
}
controller.stringRedisTemplate = template.createMock()
controller.accessRedis()
但是,我收到以下错误: org.codehaus.groovy.runtime.typehandling.GroovyCastException:无法使用类'com.tnd.viewport.ui.AppHawkControllerSpec $ _ $ spock_feature_0_1_closure2'转换对象'com.tnd.viewport.ui.AppHawkControllerSpec$_$spock_feature_0_1_closure2@1aa55dd5' class'org.springframework.data.redis.core.ValueOperations'
您能为我的方案提供解决方案吗?谢谢!
答案 0 :(得分:2)
很简单。单独模拟它们。
例如
@MockBean
private RedisTemplate<String, String> redisTemplate;
@MockBean
private ValueOperations valueOperations;
@Test
public void testRedisGetKey() {
// This will make sure the actual method opsForValue is not called and mocked valueOperations is returned
doReturn(valueOperations).when(redisTemplate).opsForValue();
// This will make sure the actual method get is not called and mocked value is returned
doReturn("someRedisValue").when(valueOperations).get(anyString());
}
答案 1 :(得分:1)
redisTemplate = mock(RedisTemplate.class);
Whitebox.setInternalState(loginService, "redisTemplate", redisTemplate);
List<Object> list = new ArrayList<Object>();
list.add(15l);
List<Object> keys = new ArrayList<>();
keys.addAll(Arrays.asList("15"));
HashOperations<Serializable, Object, Object> hashOperations =mock(HashOperations.class);
when(redisTemplate.opsForHash()).thenReturn(hashOperations);
when(hashOperations.multiGet(anyString(), anyListOf(Object.class))).thenReturn(list);