在TestExecutionListener类中为BeforeClass junit使用Autowired [英] Using Autowired in a TestExecutionListener class for BeforeClass junit

查看:167
本文介绍了在TestExecutionListener类中为BeforeClass junit使用Autowired的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在junit中执行 @BeforeClass 方法,但是使用Spring注入值,因此无法切换 private 变量到 static 。我正在尝试执行此监听器并创建一个监听器类,但我遇到了这个问题。

I need to do a @BeforeClass method in junit but inject values using Spring so can't switch private variables to static. I am trying to do this Listeners and and creating a Listener class but I am running into an issue with this.

我有需要的值在此类中自动装配因为我想要运行的方法 BeforeClass 调用 @Autowired <的变量/ code>注入。但是,由于某种原因,它不起作用,此值仍为空。有没有人遇到这样的问题呢?

I have values that I need to Autowire in this class as well because the method I want to run BeforeClass calls for a variable that is @Autowired injected. However, for some reason, it is not working and this value remains null. Has anyone run into a problem like this before?

推荐答案

这不是最干净的,但它有效:

It's not the cleanest, but it works:

public class MyTestListener extends AbstractTestExecutionListener {

    @Value("${my.value}")
    private String myValue;
    @Autowired
    private MyBean myBean;

    @Override
    public void beforeTestClass(TestContext testContext) throws Exception {
        testContext.getApplicationContext()
                .getAutowireCapableBeanFactory()
                .autowireBean(this);
    }
}

这篇关于在TestExecutionListener类中为BeforeClass junit使用Autowired的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆