Skip to content

@MockitoBean cannot be used to directly mock a FactoryBean #34653

@duoduobingbing

Description

@duoduobingbing

Problem

Replacing a bean extending FactoryBean with a @MockitoBean bean does not seem to work. My apologies if I read the docs wrong and this is not supported for @MockitoBean.

Reproducer

The following test succeeds with @MockBean but fails with @MockitoBean

@ExtendWith(SpringExtension.class)
public class BeanFactoryTest {

    @MockitoBean
    private ExampleFactoryBean exampleFactoryBean;

    @Test
    void test(@Autowired ApplicationContext applicationContext) {
        ExampleBean exampleBeanMock = Mockito.mock(ExampleBean.class);
        Mockito.when(exampleBeanMock.testMethod()).thenReturn("somethingElse");
        Mockito.when(this.exampleFactoryBean.getObjectType()).thenReturn((Class)ExampleBean.class);
        Mockito.when(this.exampleFactoryBean.getObject()).thenReturn(exampleBeanMock);

        ExampleBean bean = applicationContext.getBean(ExampleBean.class);
        Assertions.assertEquals("somethingElse", bean.testMethod());
    }

    @Configuration(proxyBeanMethods = false)
    static class TestConfig {
        @Bean
        ExampleFactoryBean exampleFactoryBean() {
            return new ExampleFactoryBean();
        }
    }

    public static class ExampleFactoryBean implements FactoryBean<ExampleBean> {

        @Override
        public ExampleBean getObject() {
            return new ExampleBean() {
                @Override
                public String testMethod() {
                    return "test";
                }
            };
        }

        @Override
        public Class<?> getObjectType() {
            return ExampleBean.class;
        }

        @Override
        public boolean isSingleton() {
            return false;
        }

    }

    public interface ExampleBean {

        String testMethod();

    }

}

The test fails with org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'exampleFactoryBean' is expected to be of type 'org.example.demo.BeanFactoryTest$ExampleFactoryBean' but was actually of type 'org.springframework.beans.factory.support.NullBean'

Workaround

Replacing @MockitoBean with @MockBean makes the test succeed.

Metadata

Metadata

Assignees

Labels

in: testIssues in the test modulestatus: invalidAn issue that we don't feel is valid

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions