Closed
Description
Environment: Spring 6.2.0-M1, Java 21
Example project: https://github.com/hantsy/spring6-sandbox/tree/master/test-bean
I tried to write a test to experience the new @MockitoSpyBean
.
@SpringJUnitConfig(classes = Config.class)
class CustomerServiceMockitoSpyTest {
@MockitoSpyBean
CustomerService customerService;
@Test
public void testCustomerService() {
when(customerService.findByEmail("dummy@example.com"))
.thenReturn(
new Customer("dummy first", "dummy last", "dummy@example.com")
);
// 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(2);
verify(customerService, times(1)).findByEmail(anyString());
verify(customerService, times(1)).findAll();
verifyNoMoreInteractions(customerService);
}
}
I tried to use customerServiceSpy
as the field name here, but it does not work. I have to use customerSerivce
here and set the bean name attribute.
Whereas, in the test that's testing @MockitoBean
in CustomerServiceMockitoTest
, using customerServiceMock
(no need set the bean name) worked well.
The spied field name should be named by developers freely, and the spied bean should override the real bean by type (not name) firstly.