Java 添加TestExecutionListener

Java 添加TestExecutionListener,java,spring,testing,spring-test,Java,Spring,Testing,Spring Test,我知道如果我需要使用一个精确的实现TestExecutionListener,它将阻止加载默认的TestExecutionListener。 如果我的测试课是 @RunWith(SpringJUnit4ClassRunner.class) @TestExecutionListeners({MyCustomTestExecutionListener.class}) @ContextConfiguration(locations = { "classpath:test-ApplicationCont

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

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({MyCustomTestExecutionListener.class})
@ContextConfiguration(locations = { "classpath:test-ApplicationContext.xml" })
public class CabinetMembershipServiceImplTest {
     ...
}
MyCustomTestExecutionListener
将是唯一加载的侦听器,它会使我的测试执行失败

当我在不指定任何TestExecutionListener的情况下启动测试,并翻阅Spring的日志时,我可以找到:

getDefaultTestExecutionListenerClassNames:
已从位置[META-INF/spring.factories]加载默认TestExecutionListener类名:
[org.springframework.test.context.web.ServletTestExecutionListener,
org.springframework.test.context.support.dirtiesContextBeforeModesteExecutionListener,
org.springframework.test.context.support.DependencyInjectionTestExecutionListener,
org.springframework.test.context.support.DirtiesContextTestExecutionListener,
org.springframework.test.context.transaction.TransactionalTestExecutionListener,
org.springframework.test.context.jdbc.sqlscriptstexecutionListener]

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

@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,而不必从默认配置显式声明每个侦听器,也不必“重写”默认侦听器

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

@TestExecutionListeners(value = { MyCustomTestExecutionListener.class }, mergeMode = MergeMode.MERGE_WITH_DEFAULTS)
有没有办法只添加一个(或多个)TestExecutionListener, 不必从默认值显式声明每个侦听器 配置或“覆盖”默认配置

是的,从Spring Framework 4.1开始,这是可能的,并且在Javadoc for
@TestExecutionListeners
和参考手册的章节中都有明确的说明。以下示例直接取自参考手册

@ContextConfiguration
@TestExecutionListeners(
listeners=MyCustomTestExecutionListener.class,
mergeMode=使用默认值合并
)
公共类MyTest{
//班集体。。。
}
问候,

Sam(SpringTestContext框架的作者)