使用返回Optional 的方法的Mockito错误

我有一个接口与以下方法

public interface IRemoteStore {  Optional get(String cacheName, String key, String ... rest); } 

实现接口的类的实例称为remoteStore。

当我用mockito模拟它并在以下时使用该方法:

 Mockito.when(remoteStore.get("a", "b")).thenReturn("lol"); 

我收到错误:

无法解析方法’thenReturn(java.lang.String)’

我认为这与get返回Optional类的实例这一事实有关,所以我尝试了这个:

 Mockito.<Optional>when(remoteStore.get("cache-name", "cache-key")).thenReturn (Optional.of("lol")); 

但是,我得到了这个错误:

当Mockito中的(可选”)无法应用于(可选”)时。

它唯一有效的时间是:

 String returnCacheValueString = "lol"; Optional returnCacheValue = Optional.of((Object) returnCacheValueString); Mockito.<Optional>when(remotestore.get("cache-name", "cache-key")).thenReturn(returnCacheValue); 

但上面会返回一个Optional”的实例,而不是Optional’。

为什么我不能直接返回Optional”的实例? 如果可以的话,我应该怎么做呢?

返回的模拟期望返回类型与模拟对象的返回类型匹配。

这是错误:

 Mockito.when(remoteStore.get("a", "b")).thenReturn("lol"); 

"lol"不是Optional ,因此它不会接受它作为有效的返回值。

你做的时候它起作用的原因

 Optional returnCacheValue = Optional.of((Object) returnCacheValueString); Mockito.>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

不确定为什么你会看到错误,但这对我编译/运行没有错误:

 public class RemoteStoreTest { public interface IRemoteStore {  Optional get(String cacheName, String key); } public static class RemoteStore implements IRemoteStore { @Override public  Optional 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.>when( remoteStore.get("b", "c") ).thenReturn( Optional.of("lol") ); Optional o1 = remoteStore.get("a", "b"); Optional o2 = remoteStore.get("b", "c"); Assert.assertEquals( "lol", o1.get() ); Assert.assertEquals( "lol", o2.get() ); Mockito.verify(remoteStore); } }