-
Notifications
You must be signed in to change notification settings - Fork 41.4k
Closed
Closed
Copy link
Labels
type: documentationA documentation updateA documentation update
Milestone
Description
A test configuration annotated with @TestConfiguration
does not override a bean, if it is defined as a separate class. Only using @TesConfiguration
on an inner class works in this case.
Not working:
@TestConfiguration
public class ExternalTestConfig {
@Bean
public MyBean myBean() {
return Mockito.mock(MyBean.class);
}
}
@SpringBootTest(properties = "spring.main.allow-bean-definition-overriding=true")
@Import(ExternalTestConfig.class)
public class ExternalTestConfigApplicationTest {
@Autowired
private MyBean myBeanMock;
@Test
void contextLoads() {
// test fails, if myBeanMock is not a mock
Mockito.verifyNoInteractions(myBeanMock);
}
}
Working:
@SpringBootTest(properties = "spring.main.allow-bean-definition-overriding=true")
class InnerClassTestConfigApplicationTest {
@Autowired
private MyBean myBeanMock;
@Test
void contextLoads() {
// test fails, if myBeanMock is not a mock
Mockito.verifyNoInteractions(myBeanMock);
}
@TestConfiguration
public static class TestConfig{
@Bean
public MyBean myBean() {
return Mockito.mock(MyBean.class);
}
}
}
My example uses spring boot 2.6.6, code can be found here: https://github.com/spring-boot-demos/demo-testing-bean-overriding
I read several blogs and articles and found some other examples, which do not work, e.g. this blog with example code which is very similar to my example code.
In my understanding, the behaviour of a class annotated with @TestConfiguration
should be the same, no matter if defined as inner or separate class.
Metadata
Metadata
Assignees
Labels
type: documentationA documentation updateA documentation update