什么是TestExecutionListeners,它们做什么?

Ali*_*han 21 spring spring-test spring-test-dbunit

据我所知,TestExecutionListeners就像@BeforeClassJUnit中的方法一样.我不明白的是为什么我需要使用DependencyInjectionTestExecutionListener,TransactionalTestExecutionListenerDirtiesContextTestExecutionListener使用DbUnitTestExecutionListener.

通常没有DbUnit,我可以创建并填充数据库.为什么我突然需要使用这些监听器CRUD为我的数据库做一些事情?

Sam*_*nen 36

TestExecutionListeners 为Spring TestContext Framework中运行的测试提供各种类型的功能.

如果您对特定侦听器的作用感兴趣,最好的方法是阅读相应类的Javadoc.此外,Spring参考手册的测试章节详细介绍了如何使用每个监听器及其功能.

在您的特定情况下,如果您不使用@DirtiesContext,那么您不需要使用DirtiesContextTestExecutionListener.至于DependencyInjectionTestExecutionListenerTransactionalTestExecutionListener,你可能会需要他们依赖注入测试(例如,通过@Autowired,@Inject,@Resource,等)和交易测试(即测试标注了@Transactional).

还要注意,默认情况下启用上述侦听器.因此,如果你一直在使用Spring TestContext Framework 而没有像DbUnit这样的自定义监听器,那么你就没有意识到监听器的存在.参考手册中有关TestExecutionListener配置的部分也应该有助于澄清事情.但请注意,默认侦听器的合并和自动检测等功能仅在Spring Framework 4.1+中可用.

问候,

Sam (Spring TestContext Framework的作者)