Make it easier to to mock java.lang.Optional as return value of a Method
See original GitHub issueWhen you do extensive testing/mocking on some APIs which return Optionals on you end up writing somehting like
Mockito.when(foo.getBaa()).thenReturn(Optional.of(myBaaValue));
many times.
this happend to me when writing many test on my Spring Applications and I mockted the Repository types into my Services (https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html).
I suggest to have a dedicated threnReturnOptional() method so you can write something like
Mockito.when(foo.getBaa()).thenReturnOptional(myBaaValue);
Issue Analytics
- State:
- Created 4 years ago
- Comments:6 (4 by maintainers)
Top Results From Across the Web
Mockito error with method that returns Optional<T>
This is easy to fix: just change it to an Optional.of("lol") instead. Mockito.when(remoteStore.get("a", "b")).thenReturn(Optional.of("lol"));.
Read more >Mockito's Java 8 Features - Baeldung
1. Overview · 2. Mocking Interface With a Default Method · 3. Return Default Values for Optional and Stream · 4. Leveraging Lambda...
Read more >How to mock repository findById thenReturn() Optional?
Try to mock a repository findById method, but no idea use thenReturn() to return an object, as it accepts an Optional ?
Read more >A Unit Testing Practitioner's Guide to Everyday Mockito - Toptal
With Mockito, creating a mock is as easy as calling a static method ... are value comparisons applicable for primitive values and instances...
Read more >Issue 497 in mockito: Mock returning java.util.Optional should ...
standard type java.util.Optional in Java 8 instead of Guava's. A stubbed method that returns Optional<?> should return Optional.empty() if
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
This is a strawman, so forgive me for that, but the same would be true for things like
thenReturnSetOf
. We would introduce an api for the most common types. We did that in the Matchers API (for set, list and map), but we regard that as a mistake.I do agree that the IDE argument is valid. So it is more an argument of IDE usefulness vs API “bloat”.
Very true (and even more: thenReturnListOf, thenReturnMapOf, thenReturnCollectionOf, …). It does not seem as a good evolution of the API. Also, we would need to add
doReturnOptionalOf
andwillReturnOptionalOf
methods for consistency.@bfarka, I hope you understand and you will continue to happily use Mockito 😃