What are TestExecutionListeners, and what do they

2019-03-23 02:54发布

问题:

As far as I understand, TestExecutionListeners act like @BeforeClass methods in JUnit. What I don't understand is why I need to use DependencyInjectionTestExecutionListener, TransactionalTestExecutionListener and DirtiesContextTestExecutionListener to use DbUnitTestExecutionListener.

Normally without DbUnit, I can create and populate the database. Why suddenly do I need to use these listeners to do some CRUD for my database?

回答1:

TestExecutionListeners provide various types of functionality to tests running in the Spring TestContext Framework.

If you are interested in what a particular listener does, the best way to find out is to read the Javadoc for the respective class. In addition, the Testing chapter of the Spring reference manual goes into detail about how to use each of the listeners and what they do.

In your particular case, if you're not using @DirtiesContext, then you don't need to use the DirtiesContextTestExecutionListener. As for DependencyInjectionTestExecutionListener and TransactionalTestExecutionListener, you will likely need them to inject dependencies into your test (e.g., via @Autowired, @Inject, @Resource, etc.) and for transactional tests (i.e., tests annotated with @Transactional).

Note as well that the aforementioned listeners are enabled by default. So if you've been using the Spring TestContext Framework without any custom listeners like the one for DbUnit, then you just never realized that the listeners existed. The section on TestExecutionListener configuration in the reference manual should also help clarify things. Note, however, that some features like merging and auto-detection of default listeners are only available in Spring Framework 4.1+.

Regards,

Sam (author of the Spring TestContext Framework)