Skip to content

Consider @Primary when @MockBean could mock more than one bean #10655

@alexandreBaronZnk

Description

@alexandreBaronZnk

Hi,

In Spring Boot 1.5.4, when we use a @MockBean on type with more than one bean but one with @Primary, the test fail.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = PrimaryMockBeanTest.TestConfig.class)
public class PrimaryMockBeanTest {

    @Test
    public void test() throws Exception {}

    @Configuration
    public static class TestConfig {

        @MockBean
        Date mockDate;

        @Bean
        @Primary
        public Date a() {
            return new Date();
        }

        @Bean
        @Qualifier("b")
        public Date b() {
            return new Date();
        }
    }
}

Exception is

Caused by: java.lang.IllegalStateException: Unable to register mock bean java.util.Date expected a single matching bean to replace but found [a, b]
	at org.springframework.boot.test.mock.mockito.MockitoPostProcessor.getBeanName(MockitoPostProcessor.java:242)
	at org.springframework.boot.test.mock.mockito.MockitoPostProcessor.registerMock(MockitoPostProcessor.java:187)
	at org.springframework.boot.test.mock.mockito.MockitoPostProcessor.register(MockitoPostProcessor.java:177)
	at org.springframework.boot.test.mock.mockito.MockitoPostProcessor.postProcessBeanFactory(MockitoPostProcessor.java:147)
	at org.springframework.boot.test.mock.mockito.MockitoPostProcessor.postProcessBeanFactory(MockitoPostProcessor.java:134)

I think this behavior is strange because I expected that @MockBean works like @Autowired : when a @Primary is define @MockBean select it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: supersededAn issue that has been superseded by another

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions