Skip to content

Clarifying documentation on including a top-level @TestConfiguration class in a test #30513

Closed
@kesslerj

Description

@kesslerj

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

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions