Spring dependency injection in Spring TestExecutionListeners not working

How can I use Spring dependency injection in the TestExecutionListener class that I wrote extending AbstractTestExecutionListener?

Spring DI doesn't seem to work with TestExecutionListener classes. Example problem:

Function 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"; } } 

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 stated in the code comment, when I ran this, it will print “simplefield null” because simplefield never gets an injection with a value.

+7
source share
2 answers

Just add auto wiring for the entire TestExecutionListener.

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

Check out the sample project on github .

+5
source

In case of Spring Boot 2 is used

 estContext.getApplicationContext() .getAutowireCapableBeanFactory() .autowireBean(this) 

initiated Spring context creation to @SpringBootTest base class. This missed some important configuration options in my case. I had to use testContext.getApplicationContext().getBean( in beforeTestClass to get the component instance).

0
source

Source: https://habr.com/ru/post/1264162/


All Articles