Skip to content

Instantly share code, notes, and snippets.

@diversit
Last active August 29, 2015 14:10
Show Gist options
  • Save diversit/ef6a1025ac9d1dc2a113 to your computer and use it in GitHub Desktop.
Save diversit/ef6a1025ac9d1dc2a113 to your computer and use it in GitHub Desktop.
Mockito: return default Optional.empty for unstubbed methods
public static final Answer DEFAULT_OPTIONAL_EMPTY_ANSWER = invocation ->
invocation.getMethod().getReturnType() == Optional.class ? Optional.empty() : null;
Mockito.mock(YourClassWithOptionalReturnValues.class, DEFAULT_OPTIONAL_EMPTY_ANSWER);
// unfortunately this does not work since Mockito's Answers enum is not extendable (yet, issue 345)
@Mock(answer = DEFAULT_OPTIONAL_EMPTY_ANSWER)
private YourClassWithOptionalReturnValues mockInstance;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment