控制器单元测试 如何用返回类型为ValueOperations的RedisTemplate opsForValue进行模拟?

问题描述 投票:5回答:2

在我的控制器中,我有如下代码.RedisTemplate stringRedisTemplate

def accessRedis()
{
   val = stringRedisTemplate.opsForValue().get('Key')
}

在我的控制器Test中,我打算注入一个模拟的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@1aa55dd5'与类'com.tnd.viewport.ui.AppHawkControllerSpec$_$spock_feature_0_1_closure2'一起投递到类'org.springframework.data.redis.core.ValueOperations'。

能否针对我的情况给我建议一个解决方案?谢谢!在我的控制器中,我有如下代码。

java unit-testing grails redis mocking
2个回答
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);

0
投票

这很简单。分别对它们进行模拟。

例如:

@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());
}
© www.soinside.com 2019 - 2024. All rights reserved.