Environment: Spring 6.2.0-M1, Java 21 Example project: https://github.com/hantsy/spring6-sandbox/tree/master/test-bean
In the following test,
@SpringJUnitConfig(classes = Config.class)
class CustomerServiceTest {
@TestBean(/*methodName = ""*/) // use methodName to specify a custom factory method.
CustomerService customerService;
// by default method name is {beanName}TestOverride
static CustomerService customerServiceTestOverride() {
return new DummyCustomerService();
}
@Test
public void test(ApplicationContext context) {
assertThat(context.getBean("customerService"))
.isSameAs(this.customerService)
.isInstanceOf(DummyCustomerService.class);
}
@Test
public void testCustomerService() {
// test bean
var testCustomer = customerService.findByEmail("dummy@example.com");
assertThat(testCustomer.firstName()).isEqualTo("dummy first");
assertThat(testCustomer.lastName()).isEqualTo("dummy last");
assertThat(customerService.findAll().size()).isEqualTo(0);
}
}
When declaring a @TestBean
varible I have to use the bean name declared in Config
, not so flexible.
Hope overriding by type is in a higher priority.
Comment From: sbrannen
When declaring a
@TestBean
varible I have to use the bean name declared inConfig
, not so flexible.
Have you seen the name
attribute in @TestBean
that allows you to specify the name of the bean to override?
Comment From: snicoll
Hope overriding by type is in a higher priority.
TestBean
really works on a bean identified by name, it doesn't do anything by type. I am a bit confused by the report as the annotation has a name
attribute that you can't have overlooked. Are we missing something?
Comment From: hantsy
When declaring a
@TestBean
varible I have to use the bean name declared inConfig
, not so flexible.Have you seen the
name
attribute in@TestBean
that allows you to specify the name of the bean to override?
yes, I have tried it. When set a name to the bean name, I can rename the variable name to others.
But several years ago when switch to Java Config instead of xml config, as a developer, I would like use type matching as first class citizen for the injecting/mocking everywhere.
Comment From: snicoll
yes, I have tried it. When set a name to the bean name, I can rename the variable name to others.
What's up with the issue title then? It really is confusing. And a duplicate of #32761 that I've requalified accordingly.