Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring dependency injection into Spring TestExecutionListeners not working

How can I use Spring dependency injection into a TestExecutionListener class I wrote extending AbstractTestExecutionListener?

Spring DI does not seem to work with TestExecutionListener classes. Example of issue:

The AbstractTestExecutionListener:

class SimpleClassTestListener extends AbstractTestExecutionListener {

    @Autowired
    protected String simplefield; // does not work simplefield = null

    @Override
    public void beforeTestClass(TestContext testContext) throws Exception {
        System.out.println("simplefield " + simplefield);
    }
}

Configuration file:

@Configuration
@ComponentScan(basePackages = { "com.example*" })
class SimpleConfig {

    @Bean
    public String simpleField() {
        return "simpleField";
    }

}

The JUnit Test file:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SimpleConfig.class })
@TestExecutionListeners(mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS, listeners = {
    SimpleClassTestListener.class })
public class SimpleTest {

    @Test
    public void test(){
        assertTrue();
    }
}

As highlighted in the code comment, when I run this, it will print "simplefield null" because simplefield never gets injected with a value.

like image 270
Dmitry K Avatar asked Feb 13 '17 13:02

Dmitry K


1 Answers

Just add autowiring for the whole TestExecutionListener.

@Override
public void beforeTestClass(TestContext testContext) throws Exception {
    testContext.getApplicationContext()
            .getAutowireCapableBeanFactory()
            .autowireBean(this);
    // your code that uses autowired fields
}

Check sample project in github.

like image 108
Ilya Zinkovich Avatar answered Oct 19 '22 19:10

Ilya Zinkovich