Mockito error with method that returns Optional<T>
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>
.