mockit.integration.springframework.FakeBeanFactory Maven / Gradle / Ivy
Show all versions of jmockit Show documentation
/*
* Copyright (c) 2006 JMockit developers
* This file is subject to the terms of the MIT license (see LICENSE.txt).
*/
package mockit.integration.springframework;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import mockit.Injectable;
import mockit.Invocation;
import mockit.Mock;
import mockit.MockUp;
import mockit.Tested;
import mockit.internal.injection.BeanExporter;
import mockit.internal.injection.TestedClassInstantiations;
import mockit.internal.state.TestRun;
import org.springframework.beans.factory.support.AbstractBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
/**
* If applied, this fake will take over calls to {@link AbstractBeanFactory#getBean(String)} and
* {@link AbstractBeanFactory#getBean(String, Class)} in any implementation class, returning instead a
* {@link Tested @Tested} or {@link Injectable @Injectable} object with the given field name, or a dependency object
* injected at any level into a @Tested
object.
*
* In case said calls come (indirectly) from a test class having no @Tested
fields, bean lookup will
* proceed into the actual getBean
implementation method.
*
* Note this fake is only useful if the code under test makes direct calls to Spring's getBean
methods.
*/
public final class FakeBeanFactory extends MockUp {
@Mock
public static Object getBean(@NonNull Invocation invocation, @NonNull String name) {
TestedClassInstantiations testedClasses = TestRun.getTestedClassInstantiations();
if (testedClasses == null) {
return invocation.proceed();
}
BeanExporter beanExporter = testedClasses.getBeanExporter();
return BeanLookup.getBean(beanExporter, name);
}
@Mock
public static T getBean(@NonNull Invocation invocation, @NonNull String name, @Nullable Class requiredType) {
TestedClassInstantiations testedClasses = TestRun.getTestedClassInstantiations();
if (testedClasses == null) {
return invocation.proceed();
}
BeanExporter beanExporter = testedClasses.getBeanExporter();
return BeanLookup.getBean(beanExporter, name, requiredType);
}
@Mock
public static T getBean(@NonNull Invocation invocation, @NonNull Class requiredType) {
TestedClassInstantiations testedClasses = TestRun.getTestedClassInstantiations();
if (testedClasses == null) {
return invocation.proceed();
}
BeanExporter beanExporter = testedClasses.getBeanExporter();
return BeanLookup.getBean(beanExporter, requiredType);
}
}