Created
February 23, 2015 21:54
-
-
Save sizovs/7adb33396317c4c2b320 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package lv.craftsmans; | |
import org.junit.Rule; | |
import org.springframework.beans.factory.config.AutowireCapableBeanFactory; | |
import org.springframework.test.context.TestContext; | |
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; | |
import org.springframework.util.ReflectionUtils; | |
import java.lang.reflect.Field; | |
public class RuleSupportingDependencyInjectionTestExecutionListener extends DependencyInjectionTestExecutionListener { | |
protected void injectDependencies(final TestContext testContext) throws Exception { | |
AutowireCapableBeanFactory beanFactory = testContext.getApplicationContext().getAutowireCapableBeanFactory(); | |
Object bean = testContext.getTestInstance(); | |
autowireTestInstance(testContext, beanFactory, bean); | |
autowireRuleFields(testContext, beanFactory, bean); | |
testContext.removeAttribute(REINJECT_DEPENDENCIES_ATTRIBUTE); | |
} | |
private void autowireTestInstance(TestContext testContext, AutowireCapableBeanFactory beanFactory, Object bean) { | |
beanFactory.autowireBeanProperties(bean, AutowireCapableBeanFactory.AUTOWIRE_NO, false); | |
beanFactory.initializeBean(bean, testContext.getTestClass().getName()); | |
} | |
private void autowireRuleFields(TestContext testContext, AutowireCapableBeanFactory beanFactory, Object bean) throws IllegalAccessException { | |
ReflectionUtils.doWithFields(bean.getClass(), field -> { | |
if (field.isAnnotationPresent(Rule.class)) { | |
Object fieldValue = field.get(bean); | |
autowireRuleField(testContext, beanFactory, field, fieldValue); | |
} | |
}); | |
} | |
private void autowireRuleField(TestContext testContext, AutowireCapableBeanFactory beanFactory, Field field, Object fieldValue) { | |
beanFactory.autowireBeanProperties(fieldValue, AutowireCapableBeanFactory.AUTOWIRE_NO, false); | |
beanFactory.initializeBean(fieldValue, testContext.getTestClass().getName() + "#" + field.getName()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment