Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Autowired in a TestExecutionListener class for BeforeClass junit

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.

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?

like image 487
user1490083 Avatar asked Feb 10 '14 20:02

user1490083


1 Answers

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);
    }
}
like image 191
bcoughlan Avatar answered Oct 28 '22 21:10

bcoughlan