Skip to content

@MockitoBean with custom @Qualifier is not injected into @Configuration class #34646

Closed
@duoduobingbing

Description

@duoduobingbing

Problem

When a @MockitoBean is annotated with a custom @Qualifier it cannot be injected into a @Configuration class when there is a normal bean with said qualifier.

Reproducer

Reproducer Test
@ExtendWith(SpringExtension.class)
public class QualifierAnnotationTest {

    @MockitoBean
    @MyQualifier
    private IExample myExample;

    @Autowired
    private MyExampleCaller caller;

    @Test
    public void test() {

    }

    public interface IExample {

        String value();

    }

    public static class MyExampleCaller  {

        IExample example;

        public MyExampleCaller(IExample example) {
            this.example = example;
        }

    }

    @Qualifier
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MyQualifier {

    }

    @MyQualifier
    public static class QualifierExample implements IExample {

        @Override
        public String value() {
            return "QualifierExample";
        }

    }

    @Configuration(proxyBeanMethods = false)
    static class TestConfig {

        @Bean
        public QualifierExample toBeReplacedByMock() {
            return new QualifierExample();
        }

        @Bean
        MyExampleCaller controller(@MyQualifier IExample example) {
            return new MyExampleCaller(example);
        }

    }
}

The test fails with:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.example.qualifiermockitobeanbug.QualifierAnnotationTest$IExample' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.example.qualifiermockitobeanbug.QualifierAnnotationTest.MyQualifier()}

Workaround

Replacing @MockitoBean with @MockBean causes the test to succeed.

Metadata

Metadata

Assignees

Labels

in: testIssues in the test moduletype: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions