Allow MockitoBean to create a mock for a bean that does not exist

This commit aligns the by-type lookup for bean overrides with what was
done when a bean name is present. It now correctly generate a bean
name rather than failing because no bean of that type exists.

Closes gh-32990
This commit is contained in:
Stéphane Nicoll
2024-06-10 09:53:27 +02:00
parent bc98410acf
commit 536de9ac80
4 changed files with 54 additions and 43 deletions

View File

@@ -51,8 +51,8 @@ class FailingTestBeanByTypeIntegrationTests {
cause(
instanceOf(IllegalStateException.class),
message("""
Unable to select a bean definition to override: found 0 bean definitions \
of type %s (as required by annotated field '%s.example')"""
Unable to override bean: no bean definitions of type \
%s (as required by annotated field '%s.example')"""
.formatted(ExampleService.class.getName(), testClass.getSimpleName())))));
}

View File

@@ -43,19 +43,6 @@ import static org.junit.platform.testkit.engine.TestExecutionResultConditions.me
*/
class FailingMockitoBeanByTypeIntegrationTests {
@Test
void zeroCandidates() {
Class<?> testClass = ZeroCandidatesTestCase.class;
EngineTestKitUtils.executeTestsForClass(testClass).assertThatEvents().haveExactly(1,
finishedWithFailure(
cause(
instanceOf(IllegalStateException.class),
message("""
Unable to select a bean definition to override: found 0 bean definitions \
of type %s (as required by annotated field '%s.example')"""
.formatted(ExampleService.class.getName(), testClass.getSimpleName())))));
}
@Test
void tooManyCandidates() {
Class<?> testClass = TooManyCandidatesTestCase.class;
@@ -70,22 +57,6 @@ class FailingMockitoBeanByTypeIntegrationTests {
}
@SpringJUnitConfig
static class ZeroCandidatesTestCase {
@MockitoBean
ExampleService example;
@Test
void test() {
assertThat(example).isNotNull();
}
@Configuration
static class Config {
}
}
@SpringJUnitConfig
static class TooManyCandidatesTestCase {

View File

@@ -49,6 +49,9 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
@SpringJUnitConfig
public class MockitoBeanByTypeIntegrationTests {
@MockitoBean
AnotherService serviceIsNotABean;
@MockitoBean
ExampleService anyNameForService;
@@ -60,6 +63,17 @@ public class MockitoBeanByTypeIntegrationTests {
@CustomQualifier
StringBuilder ambiguousMeta;
@Test
void mockIsCreatedWhenNoCandidateIsFound() {
assertThat(this.serviceIsNotABean)
.satisfies(o -> assertThat(Mockito.mockingDetails(o).isMock()).as("isMock").isTrue());
when(this.serviceIsNotABean.hello()).thenReturn("Mocked hello");
assertThat(this.serviceIsNotABean.hello()).isEqualTo("Mocked hello");
verify(this.serviceIsNotABean, times(1)).hello();
verifyNoMoreInteractions(this.serviceIsNotABean);
}
@Test
void overrideIsFoundByType(ApplicationContext ctx) {
@@ -109,6 +123,11 @@ public class MockitoBeanByTypeIntegrationTests {
verifyNoMoreInteractions(this.ambiguousMeta);
}
interface AnotherService {
String hello();
}
@Configuration
static class Config {