添加TestExecutionListener

时间:2016-04-08 14:51:41

标签: java spring testing spring-test

我知道如果我需要使用精确的实现TestExecutionListener,它将阻止加载默认的TestExecutionListeners。 如果我的测试类是

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({MyCustomTestExecutionListener.class})
@ContextConfiguration(locations = { "classpath:test-ApplicationContext.xml" })
public class CabinetMembershipServiceImplTest {
     ...
}

MyCustomTestExecutionListener将是唯一加载的侦听器,它会使我的测试执行失败。

当我启动我的测试时,指定任何TestExecutionListener,并且我在Spring的日志中挖掘,我可以找到:

getDefaultTestExecutionListenerClassNames : Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]

因此,如果我想添加我的TestExecutionListener,我需要在我的测试类中指定(除了想要的实现)所有这些默认的TestExectionListener:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
    ServletTestExecutionListener.class,
    DirtiesContextBeforeModesTestExecutionListener.class,
    DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class,
    SqlScriptsTestExecutionListener.class,
    MyCustomTestExecutionListener.class})
@ContextConfiguration(locations = { "classpath:test-ApplicationContext.xml" })
public class CabinetMembershipServiceImplTest {
     ...
}

是否有一种方法可以只添加一个(或多个)TestExecutionListener,而无需从默认配置中显式声明每个侦听器,也不需要#34;覆盖"默认的?

2 个答案:

答案 0 :(得分:5)

import org.springframework.test.context.TestExecutionListeners.MergeMode;

@TestExecutionListeners(value = { MyCustomTestExecutionListener.class }, mergeMode = MergeMode.MERGE_WITH_DEFAULTS)

答案 1 :(得分:3)

  

有没有办法只添加一个(或多个)TestExecutionListener,   不必从默认情况下显式声明每个侦听器   配置还是“覆盖”默认值?

是的,这可以从Spring Framework 4.1开始,并且在@TestExecutionListeners的Javadoc和参考手册的Merging TestExecutionListeners部分都有明确的文档记录。以下示例直接取自参考手册。

@ContextConfiguration
@TestExecutionListeners(
    listeners = MyCustomTestExecutionListener.class,
    mergeMode = MERGE_WITH_DEFAULTS
)
public class MyTest {
  // class body...
}

此致

Sam( Spring TestContext Framework的作者

相关问题