spring-framework icon indicating copy to clipboard operation
spring-framework copied to clipboard

@MockitoBean should allow a custom answer

Open adrian-tarau opened this issue 6 months ago • 4 comments

Currently, there is no way to request a few mocks, provide answers (to share common setups), and automatically inject these mocks where needed.

@MockitoBean should have a property called answer, of type Class<? extends Answer>, and use the class (create an instance) when a mock is created in MockitoBeanOverrideHandler.createMock.

adrian-tarau avatar May 27 '25 21:05 adrian-tarau

Hi @adrian-tarau,

We don't consider it very common to configure a custom Answer with Mockito, and the documentation for Mockito also states something along those lines.

However, we do support the standard Answers enum from Mockito.

Are you familiar with @MockitoBean( answers = ... )?

If Answers does not meet your needs, what is it exactly that you are trying achieve when you say "to share common setups"?

sbrannen avatar May 28 '25 15:05 sbrannen

@sbrannen I think Mockito says something like "in rare cases, etc., etc." :) However, it does not mean it is not needed or part of the API. @MockitoBean( answers = ... ) only provides default behaviours (also using an Answer). And by the way, RETURNS_SMART_NULLS should be used instead of RETURNS_DEFAULTS as a default value, as it allows for safer behavior (my 2 cents).

The purpose of using custom answers is to provide shared behaviours (just like Mockito does internally) across repositories and services. I do not want to keep repeating the same pattern across tests within modules. For example:

 @MockitoBean private RepositoryA repoA;
 @MockitoBean private RepositoryB repoB;

 @Autowired private ServiceA serviceA;

The service is created, mocks are injected, and since ServiceA implements InitializingBean, the repositories will be called before behaviors can be added. If I could attach behaviours in the annotation, the mock would be done using a common behaviour.

I can provide a patch if the enhancement is approved/accepted. There are just a few lines of code, and while it may not be helpful or useful for everyone, it might be beneficial in some cases.

adrian-tarau avatar May 29 '25 13:05 adrian-tarau

@sbrannen, since the default answer in Mockito can be changed, please disregard RETURNS_SMART_NULLS vs RETURNS_DEFAULTS. Smart nulls are/should always be more useful.

adrian-tarau avatar May 29 '25 14:05 adrian-tarau

Forgot to mention: I know I can use @ TestBean and take over the creation of the mocked bean, but it's too much boilerplate code. Ultimately, the method I will use creates a mock of the bean (in this case, the repository) with a shared answer. It would be much better to provide an answer class with @MockitoBean.

adrian-tarau avatar May 30 '25 19:05 adrian-tarau