在我的 Controller 中,我有如下代码。
RedisTemplate stringRedisTemplate
def accessRedis()
{
val = stringRedisTemplate.opsForValue().get('Key')
}
在我的 Controller Test中,我打算注入(inject)一个模拟的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.type.handling.GroovyCastException:无法将对象'com.tnd.viewport.ui.AppHawkControllerSpec$_$spock_feature_0_1_closure2@1aa55dd5'与类型'com.tnd.viewport.ui.AppHawkControllerSpec $ _ $ spock_feature_0_1类'org.springframework.data.redis.core.ValueOperations'
您能为我的方案提供解决方案吗?谢谢!
最佳答案
这很简单。分别模拟它们。
例如。
@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());
}