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

Allow `@MockitoBean` to replace all beans of a given type

Open russfactory opened this issue 4 weeks ago • 0 comments

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.

russfactory avatar Nov 12 '25 18:11 russfactory