使用返回Optional< T>的方法的Mockito错误 [英] Mockito error with method that returns Optional<T>

查看:953
本文介绍了使用返回Optional< T>的方法的Mockito错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下方法的界面

I have an interface with the following method

public interface IRemoteStore {

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

}

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

The instance of the class implementing the interface is called remoteStore.

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

When I mock this with mockito and use the method when:

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

我收到错误:


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

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

我认为这与get返回Optional类的实例这一事实我试过这个:

I thought it has to do with the fact that get returns an instance of the Optional class so I tried this:

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

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

But, I get this error instead:

当Mockito中的(可选'<'String'>')无法应用于(可选'<'对象'>')时。

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'<'Object'>'的实例,而不是Optional'< 'STRING'>。

But above returns an instance of Optional '<'Object'>' and not Optional '<'String'>.

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

Why couldn't I just return an instance of Optional '<'String'>' directly? If I could, how should I go about doing that?

推荐答案

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

Mocks that return have the expectation that the return type matches the mocked object's return type.

这是错误:

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

lol不是可选< String> ,因此它不会接受它作为有效的返回值。

"lol" isn't an Optional<String>, so it won't accept that as a valid return value.

它的工作原因你做了

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

归因于 returnCacheValue 可选

这很容易解决:只需将其更改为 Optional.of( lol)而不是。

This is easy to fix: just change it to an Optional.of("lol") instead.

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

您也可以取消证人类型;上面的结果将被推断为可选< String>

You can also do away with the type witnesses as well; the result above will be inferred to be Optional<String>.

这篇关于使用返回Optional&lt; T&gt;的方法的Mockito错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆