我有一个与以下方法的接口
public interface IRemoteStore {
<T> Optional<T> get(String cacheName, String key, String ... rest);
}实现接口的类的实例称为remoteStore。
当我用mockito来模拟它时,当我使用这个方法时:
Mockito.when(remoteStore.get("a", "b")).thenReturn("lol");我知道错误:
无法解析方法
thenReturn(java.lang.String)
我认为这与get返回可选类的实例这一事实有关,因此我尝试如下:
Mockito.<Optional<String>>when(remoteStore.get("cache-name", "cache-key")).thenReturn
(Optional.of("lol"));但是,我得到了这个错误:
Mockito中的时间(
Optional<String>)不能应用于(Optional<Object>)。
它唯一起作用的地方就是这样:
String returnCacheValueString = "lol";
Optional<Object> returnCacheValue = Optional.of((Object) returnCacheValueString);
Mockito.<Optional<Object>>when(remotestore.get("cache-name", "cache-key")).thenReturn(returnCacheValue);但是上面返回的是Optional<Object>的一个实例,而不是Optional<String>。
为什么我不能直接返回一个Optional<String>实例呢?如果可以的话,我该怎么做?
发布于 2015-06-19 20:52:02
返回的模拟期望返回类型与模拟对象的返回类型匹配。
这是个错误:
Mockito.when(remoteStore.get("a", "b")).thenReturn("lol");"lol"不是一个Optional<String>,所以它不会接受它作为一个有效的返回值。
当你这么做的时候它起作用的原因
Optional<Object> returnCacheValue = Optional.of((Object) returnCacheValueString);
Mockito.<Optional<Object>>when(remotestore.get("cache-name", "cache-key")).thenReturn(returnCacheValue);是因为returnCacheValue是Optional。
这很容易修复:只需将其改为Optional.of("lol")即可。
Mockito.when(remoteStore.get("a", "b")).thenReturn(Optional.of("lol"));你也可以取消类型的证人以及。以上结果将被推断为Optional<String>。
发布于 2015-06-19 20:41:29
不知道为什么会看到错误,但这会为我编译/运行没有错误的代码:
public class RemoteStoreTest {
public interface IRemoteStore {
<T> Optional<T> get(String cacheName, String key);
}
public static class RemoteStore implements IRemoteStore {
@Override
public <T> Optional<T> get(String cacheName, String key) {
return Optional.empty();
}
}
@Test
public void testGet() {
RemoteStore remoteStore = Mockito.mock(RemoteStore.class);
Mockito.when( remoteStore.get("a", "b") ).thenReturn( Optional.of("lol") );
Mockito.<Optional<Object>>when( remoteStore.get("b", "c") ).thenReturn( Optional.of("lol") );
Optional<String> o1 = remoteStore.get("a", "b");
Optional<Object> o2 = remoteStore.get("b", "c");
Assert.assertEquals( "lol", o1.get() );
Assert.assertEquals( "lol", o2.get() );
Mockito.verify(remoteStore);
}
}https://stackoverflow.com/questions/30946167
复制相似问题