2015-06-19 116 views
9

我有以下方法与方法错误的Mockito返回可选<T>

public interface IRemoteStore { 

<T> Optional<T> get(String cacheName, String key, String ... rest); 

} 

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

当我嘲笑这个用的Mockito和使用方法时:

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

我得到的错误:

Cannot resolved the method 'thenReturn(java.lang.String)'

我认为它与该得到回报的一个实例的事实做可选类,所以我试过这个:

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

但是,我得到这个错误,而不是:

when (Optional '<'String'>') in Mockito cannot be applied to (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'<'String'>'的实例?如果可以的话,我应该怎么做呢?

+0

您是不是在第一个代码块中缺少一个括号? – npe

+0

此外,不要混淆'java.util.Optional'和'com.google.common.base.Optional',因为后者需要在这里导入。 – jckuester

回答

10

嘲笑返回有期望的返回类型的嘲笑对象的返回类型相匹配。

这里的错误:

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>

+0

嘿谢谢你的回复。是的,我意识到错误并改变了它。什么错了,我没有将我的项目语言级别设置为Java 8. –

+0

我不会从阅读你的问题知道这一点。 'Optional'是Google Guava中的一个类 - 一个非常受欢迎的第三方库 - 它与Java 7兼容。 – Makoto

0

不知道为什么你看到的错误,但这种编译/运行无差错对我来说:

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); 
    } 
} 
+0

嘿唐,谢谢你的回应。这让我意识到我的IDE具有设置为java 7的项目语言级别,而不是java 8。但是,我使用Guava中的Optional,而不是Java 8,但这是一个不同的问题。谢谢。 –

+2

解释*为什么*它的工作比说它确实要好。OP可能不是唯一有此问题的人;其他人可能会进来并在未来也有类似的问题。 – Makoto