@Autowired bean is null in Test Listener class

北慕城南 提交于 2019-12-13 04:59:24

问题


This question was asked before Using Autowired in a TestExecutionListener class for BeforeClass junit however it wasn't answered. I am facing the same problem but haven't figured out the solution

Example: I am getting null mapper.

public class CustomExecutionListener extends AbstractTestExecutionListener {


@Autowired
private Mapper mapper;

@Override
public void beforeTestClass(TestContext testContext) {}
... some code...
}

Test Class: Note: AppConfig contains the Mapper Bean defined.

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners(listeners = {DependencyInjectionTestExecutionListener.class, CustomExecutionListener.class})
@ContextConfiguration(classes = {AppConfig.class})
public class AccountControllerTest {
....
}

回答1:


Dependency injection is not supported for TestExecutionListener instances.

Dependency injection is only supported for test instances.

Thus, if your CustomExecutionListener needs to access a bean from the ApplicationContext, it will have to look it up manually -- for example, like this:

public void beforeTestClass(TestContext testContext) {

    Mapper mapper = testContext.getApplicationContext().getBean(Mapper.class);

    // ... some code...

}

Regards,

Sam (author of the Spring TestContext Framework)




回答2:


You can also try this: Mapper mapper = Mappers.getMapper(Mapper.class);



来源:https://stackoverflow.com/questions/23923510/autowired-bean-is-null-in-test-listener-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!