java - Mockito error with method that returns Optional<T> -
i have interface following method
public interface iremotestore { <t> optional<t> get(string cachename, string key, string ... rest); }
the instance of class implementing interface called remotestore.
when mock mockito , use method when:
mockito.when(remotestore.get("a", "b").thenreturn("lol");
i error:
cannot resolved method 'thenreturn(java.lang.string)'
i thought has fact returns instance of optional class tried this:
mockito.<optional<string>>when(remotestore.get("cache-name", "cache-key")).thenreturn (optional.of("lol"));
but, error instead:
when (optional '<'string'>') in mockito cannot applied (optional'<'object'>').
the time worked this:
string returncachevaluestring = "lol"; optional<object> returncachevalue = optional.of((object) returncachevaluestring); mockito.<optional<object>>when(remotestore.get("cache-name", "cache-key")).thenreturn(returncachevalue);
but above returns instance of optional '<'object'>' , not optional '<'string'>.
why couldn't return instance of optional '<'string'>' directly? if could, how should go doing that?
mocks return have expectation return type matches mocked object's return type.
here's mistake:
mockito.when(remotestore.get("a", "b")).thenreturn("lol");
"lol"
isn't optional<string>
, won't accept valid return value.
the reason worked when did
optional<object> returncachevalue = optional.of((object) returncachevaluestring); mockito.<optional<object>>when(remotestore.get("cache-name", "cache-key")).thenreturn(returncachevalue);
is due returncachevalue
being optional
.
this easy fix: change optional.of("lol")
instead.
mockito.when(remotestore.get("a", "b")).thenreturn(optional.of("lol"));
you can away type witnesses well; result above inferred optional<string>
.
Comments
Post a Comment