【问题标题】:@Autowired bean is null in Test Listener class@Autowired bean 在测试侦听器类中为空
【发布时间】:2014-05-28 23:32:08
【问题描述】:

这个问题是在Using Autowired in a TestExecutionListener class for BeforeClass junit 之前提出的,但没有得到回答。我也遇到了同样的问题,但是还没找到解决办法

示例:我得到空映射器。

public class CustomExecutionListener extends AbstractTestExecutionListener {


@Autowired
private Mapper mapper;

@Override
public void beforeTestClass(TestContext testContext) {}
... some code...
}

测试类:注意:AppConfig 包含定义的 Mapper Bean。

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners(listeners = {DependencyInjectionTestExecutionListener.class, CustomExecutionListener.class})
@ContextConfiguration(classes = {AppConfig.class})
public class AccountControllerTest {
....
}

【问题讨论】:

    标签: spring unit-testing autowired spring-test


    【解决方案1】:

    TestExecutionListener 实例不支持依赖注入。

    仅测试实例支持依赖注入。

    因此,如果您的 CustomExecutionListener 需要从 ApplicationContext 访问 bean,则必须手动查找它——例如,像这样:

    public void beforeTestClass(TestContext testContext) {
    
        Mapper mapper = testContext.getApplicationContext().getBean(Mapper.class);
    
        // ... some code...
    
    }
    

    问候,

    Sam(Spring TestContext 框架的作者)

    【讨论】:

    • 其实我也在做类似的事情:AutowireCapableBeanFactory beanFactory = testContext.getApplicationContext().getAutowireCapableBeanFactory(); beanFactory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false); beanFactory.initializeBean(this, this.getClass().getName());
    【解决方案2】:

    你也可以试试这个:Mapper mapper = Mappers.getMapper(Mapper.class);

    【讨论】:

    • 一个解释会引起观众的注意。并始终尝试写一个描述性的答案。
    猜你喜欢
    • 2020-11-04
    • 2016-09-06
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 2014-09-24
    • 2011-01-16
    相关资源
    最近更新 更多