Spring dependency injection into Spring TestExecut

2019-02-17 04:56发布

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.

1条回答
ゆ 、 Hurt°
2楼-- · 2019-02-17 05:16

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.

查看更多
登录 后发表回答