spring-projects / spring-projects/spring-framework
Allow `@MockitoBean` to replace all beans of a given type
Nobody has claimed this yet.
- Dominant language
- Java
- Stars
- 60.2k
- Forks
- 38.8k
- Avg merge
- 5d 2h
- Merged PRs (30d)
- 27
Description
I might be missing something fundamental but I have use cases where I have multiple beans implementing a type (interface) but I want to use a mock for the type in a test. However, if there are multiple matches for a bean using @MockitoBean, Spring throws an exception and requires that a specific bean be qualified (using @Qualifier, the name attribute in @MockitoBean, or changing the field name to a specific bean of the declared type). I don't understand why I have to qualify and would like to just have Spring replace all instances of the bean with a mock. I understand there may be injection points in the application that declare a specific implementation with a narrowed type so maybe that could yield an error. But if all uses declare the generic type (interface, etc.) even if using name qualifiers, I think they could get the mock instead. Maybe, this feature could be an opt-in via an attribute on @MockitoBean such as boolean replaceAll() or something. My workaround is to create a dummy @Primary bean in a nested @TestConfiguration class so there is just one bean but it just gets mocked anyway (I still mock so I can use Mockito verify API) so seems like unnecessary code.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reading the @MockitoBean replacement behavior and how @Qualifier, the name attribute, and field names resolve multiple matching beans. Define the opt-in semantics for replacing all beans, including generic interface injection, named qualifiers, and narrowed implementation types; done means the intended cases and error behavior are covered by tests.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java, spring
- Domain
- backend, testing
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100