Only attempt mock reset on instantiated singletons

Update ResetMocksTestExecutionListener to only attempt a mock reset when
a singleton has actually been created.

Fixes gh-5870
pull/5980/head
Phillip Webb 9 years ago
parent bcfa2e6676
commit 2fc86b2d5a

@ -16,11 +16,14 @@
package org.springframework.boot.test.mock.mockito;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.mockito.Mockito;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.context.TestContext;
@ -56,11 +59,11 @@ public class ResetMocksTestExecutionListener extends AbstractTestExecutionListen
MockReset reset) {
ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();
String[] names = beanFactory.getBeanDefinitionNames();
Set<String> instantiatedSingletons = new HashSet<String>(
Arrays.asList(beanFactory.getSingletonNames()));
for (String name : names) {
BeanDefinition definition = beanFactory.getBeanDefinition(name);
String scope = definition.getScope();
if (AbstractBeanDefinition.SCOPE_DEFAULT.equals(scope)
|| BeanDefinition.SCOPE_SINGLETON.equals(scope)) {
if (definition.isSingleton() && instantiatedSingletons.contains(name)) {
Object bean = beanFactory.getBean(name);
if (reset.equals(MockReset.get(bean))) {
Mockito.reset(bean);

@ -26,6 +26,7 @@ import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
@ -80,6 +81,13 @@ public class ResetMocksTestExecutionListenerTests {
return mock(ExampleService.class);
}
@Bean
@Lazy
public ExampleService fail() {
// gh-5870
throw new RuntimeException();
}
}
}

Loading…
Cancel
Save