Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - Mockito error with method that returns Optional<T>

I have an interface with the following method

public interface IRemoteStore {

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

}

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

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

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

I get the error:

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

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:

when (Optional '<'String'>') in Mockito cannot be applied to (Optional'<'Object'>').

The only time it worked was with 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 an instance of Optional '<'Object'>' and not Optional '<'String'>.

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

question from:https://stackoverflow.com/questions/30946167/mockito-error-with-method-that-returns-optionalt

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...