项目概况

JUnit单测类属性注入

2026-01-291 min read未分类
源码分析

通过前面的阅读我们已经能拿到了所有的容器启动参数。那么我们可以思考下。我们自己的 单测类其实并没有交给容器来管理,那么我们的单测类中的属性都是什么时候注入的呢?

答案就在 TestExecutionListener

java
1public interface TestExecutionListener { 2 3 default void beforeTestClass(TestContext testContext) throws Exception { 4 } 5 6 default void prepareTestInstance(TestContext testContext) throws Exception { 7 } 8 9 default void beforeTestMethod(TestContext testContext) throws Exception { 10 } 11 12 default void beforeTestExecution(TestContext testContext) throws Exception { 13 } 14 15 default void afterTestExecution(TestContext testContext) throws Exception { 16 } 17 18 default void afterTestMethod(TestContext testContext) throws Exception { 19 } 20 21 default void afterTestClass(TestContext testContext) throws Exception { 22 } 23 24}

通过名字我们发现了貌似一个可以进行依赖注入的类。没错就是在这里,在单侧方法执行前。通过

java
1public class DependencyInjectionTestExecutionListener extends AbstractTestExecutionListener { 2 @Override 3 public void beforeTestMethod(TestContext testContext) throws Exception { 4 if (Boolean.TRUE.equals(testContext.getAttribute(REINJECT_DEPENDENCIES_ATTRIBUTE))) { 5 if (logger.isDebugEnabled()) { 6 logger.debug("Reinjecting dependencies for test context [" + testContext + "]."); 7 } 8 injectDependencies(testContext); 9 } 10 } 11 12 protected void injectDependencies(TestContext testContext) throws Exception { 13 Object bean = testContext.getTestInstance(); 14 Class<?> clazz = testContext.getTestClass(); 15 AutowireCapableBeanFactory beanFactory = testContext.getApplicationContext().getAutowireCapableBeanFactory(); 16 beanFactory.autowireBeanProperties(bean, AutowireCapableBeanFactory.AUTOWIRE_NO, false); 17 beanFactory.initializeBean(bean, clazz.getName() + AutowireCapableBeanFactory.ORIGINAL_INSTANCE_SUFFIX); 18 testContext.removeAttribute(REINJECT_DEPENDENCIES_ATTRIBUTE); 19 } 20}