Mockito error with method that returns Optional<T>

半腔热情 提交于 2019-12-04 22:22:13
Makoto

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

Here's the mistake:

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

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

The reason it worked when you did

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

is due to returnCacheValue being an Optional.

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

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

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

Not sure why you are seeing errors, but this compiles/runs error-free for me:

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);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!