1

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 {
....
}
Community
  • 1
  • 1
R P
  • 45
  • 1
  • 9

2 Answers2

3

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)

Sam Brannen
  • 29,611
  • 5
  • 104
  • 136
  • I was actually do similar thing: `AutowireCapableBeanFactory beanFactory = testContext.getApplicationContext().getAutowireCapableBeanFactory(); beanFactory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false); beanFactory.initializeBean(this, this.getClass().getName());` – R P May 30 '14 at 18:16
0

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

Sanket Patel
  • 227
  • 1
  • 14