Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Registering additional "empty values" #1766

Open
Stephan202 opened this issue Aug 25, 2019 · 1 comment
Open

Registering additional "empty values" #1766

Stephan202 opened this issue Aug 25, 2019 · 1 comment

Comments

@Stephan202
Copy link
Contributor

Context

Mockito provides various custom Answer implementations. These are very helpful, especially when working with legacy code. The most powerful of these are RETURNS_SMART_NULLS, RETURNS_MOCKS and RETURNS_DEEP_STUBS, because they are "recursive": they produce mocks which can return other mocks which are then governed by the same Answer.

Further more, RETURNS_SMART_NULLS and RETURNS_MOCKS return well-known empty values for assorted types, as implemented by the classes ReturnsEmptyValues and ReturnsMoreEmptyValues. The advantage of such values over mocks is that they are guaranteed to adhere to their type's contract. (For example, this avoids returning a List for which isEmpty() is false while .iterator() returns a (behaviorally) empty iterator; something RETURNS_MOCKS otherwise would do.)

Observation

Mockito also allows one to define custom Answers, and it is also possible to make one's own Answers produce mocks which "recursively" use that same Answer instance. But (as best as I can tell), if such implementations also want to return empty values for well-known types, then they have to directly reference ReturnsEmptyValues or ReturnsMoreEmptyValues, which is not "allowed" because these classes reside inside org.mockito.internal.*.

As a result there does not seem to be a "proper" way to create an Answer implementation which mostly behaves like e.g. RETURNS_MOCKS, but which returns well-known empty values for additional specific types. Use cases include returning empty Guava immutable collections or empty Reactor/RxJava types.

Request

I'd be nice if there were a (sanctioned) way to produce Answers which both (a) define additional "well-known empty values" and (b) have the aforementioned "recursive" behavior. Potential approaches include:

  1. An SPI using which the set of types known to Returns(More)EmptyValues can be extended.
  2. Expose Returns(More)EmptyValues directly as a new Answers.RETURNS_EMPTY_VALUES enum value.
  3. Expose Returns(More)EmptyValues some other way.
@TimvdLippe
Copy link
Contributor

I would be okay with 2. The delegate pattern seems like an appropriate solution here. We use this pattern also in our internal answers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants