Prior to this commit, @MockitoBean and @MockitoSpyBean could be
declared on fields or at the type level (on test classes and test
interfaces), but not on constructor parameters. Consequently, a test
class could not use constructor injection for bean overrides.
To address that, this commit introduces support for @MockitoBean and
@MockitoSpyBean on constructor parameters in JUnit Jupiter test
classes. Specifically, the Bean Override infrastructure has been
overhauled to support constructor parameters as declaration sites and
injection points alongside fields, and the SpringExtension now
recognizes composed @BeanOverride annotations on constructor
parameters in supportsParameter() and resolves them properly in
resolveParameter(). Note, however, that this support has not been
introduced for @TestBean.
For example, the following which uses field injection:
@SpringJUnitConfig(TestConfig.class)
class BeanOverrideTests {
@MockitoBean
CustomService customService;
// tests...
}
Can now be rewritten to use constructor injection:
@SpringJUnitConfig(TestConfig.class)
class BeanOverrideTests {
private final CustomService customService;
BeanOverrideTests(@MockitoBean CustomService customService) {
this.customService = customService;
}
// tests...
}
With Kotlin this can be achieved even more succinctly via a compact
constructor declaration:
@SpringJUnitConfig(TestConfig::class)
class BeanOverrideTests(@MockitoBean val customService: CustomService) {
// tests...
}
Of course, if one is a fan of so-called "test records", that can also
be achieved succinctly with a Java record:
@SpringJUnitConfig(TestConfig.class)
record BeanOverrideTests(@MockitoBean CustomService customService) {
// tests...
}
Closes gh-36096