Skip to content

@MockitoSpyBean does not work in tests with @ContextHierarchy #34597

Closed as not planned
@tvahrst

Description

@tvahrst

Using @MockitoSpyBean in tests with parent-child contexts defined with @ContextHierarchy fails with an IllegalStateException:

java.lang.IllegalStateException: Unable to select a bean to wrap: there are no beans of type ...
	at org.springframework.test.context.bean.override.BeanOverrideBeanFactoryPostProcessor.wrapBean(BeanOverrideBeanFactoryPostProcessor.java:273)
	at org.springframework.test.context.bean.override.BeanOverrideBeanFactoryPostProcessor.registerBeanOverride(BeanOverrideBeanFactoryPostProcessor.java:116)
	at org.springframework.test.context.bean.override.BeanOverrideBeanFactoryPostProcessor.postProcessBeanFactory(BeanOverrideBeanFactoryPostProcessor.java:100)

It seems that the BeanOverrideBeanFactoryPostProcessor tries to wrap the target bean for each context in the hierarchy - failing for the context in which the target bean does not exist.

Code to reproduce this issue:

@ContextHierarchy({
	@ContextConfiguration(classes = Config1.class),
	@ContextConfiguration(classes = Config2.class)
})
@ExtendWith(SpringExtension.class)
class TestMockitoSpyBeanJUnit5 {

	// @SpyBean // works
	@MockitoSpyBean
	private MyService myService;

	@Test
	void test() {
		System.out.print(myService.getValue());
	}


	@Configuration
	public static class Config1 {
		@Bean
		public MyService myService() {
			return new MyService();
		}
	}

	@Configuration
	public static class Config2 {
	}


	public static class MyService {
		public String getValue() {
			return "New";
		}
	}
}

The exception occurs regardless of the order of Config1.class and Config2.class.

Metadata

Metadata

Assignees

No one assigned

    Labels

    in: testIssues in the test modulestatus: 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