Skip to content

Spies are not reset after test execution when using @SpyBean #7374

@mjgp2

Description

@mjgp2

Spies created with @SpyBean are not added to the MockitoBeans which are then reset at the end of test execution like Mocks are, rendering them useless for invocation counts.

Compare from org.springframework.boot.test.mock.mockito.MockitoPostProcessor:

private void registerMock(ConfigurableListableBeanFactory beanFactory,
		BeanDefinitionRegistry registry, MockDefinition definition, Field field) {
	RootBeanDefinition beanDefinition = createBeanDefinition(definition);
	String beanName = getBeanName(beanFactory, registry, definition, beanDefinition);
	beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(1,
			beanName);
	if (registry.containsBeanDefinition(beanName)) {
		registry.removeBeanDefinition(beanName);
	}
	registry.registerBeanDefinition(beanName, beanDefinition);
	Object mock = createMock(definition, beanName);
	beanFactory.registerSingleton(beanName, mock);
	this.mockitoBeans.add(mock);
	this.beanNameRegistry.put(definition, beanName);
	if (field != null) {
		this.fieldRegistry.put(field, new RegisteredField(definition, beanName));
	}
}

and

private void registerSpy(SpyDefinition definition, Field field, String beanName) {
	this.spies.put(beanName, definition);
	this.beanNameRegistry.put(definition, beanName);
	if (field != null) {
		this.fieldRegistry.put(field, new RegisteredField(definition, beanName));
	}
}

You can see for @MockBean that we register the mocks (this.mockitoBeans.add(mock);) but for @SpyBean the mock is never registered, and hence is not reset when the beans contained in the MockitoBeans instance are.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions