为什么 ApplicationListener
作为一个 bean 工作,而 TestExecutionListener
不是吗?
以下代码没有显示来自 MyListener1
的任何消息,因为 TestExecutionListener
应通过 @TestExecutionListeners
注册.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestExecutionListenerTry._Config.class)
public class TestExecutionListenerTry {
public static class Bean1 {
}
public static class Bean2 {
}
public static class MyListener1 implements TestExecutionListener {
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
System.out.println("beforeTestClass " + testContext.toString());
}
@Override
public void prepareTestInstance(TestContext testContext) throws Exception {
System.out.println("prepareTestInstance " + testContext.toString());
}
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
System.out.println("beforeTestMethod " + testContext.toString());
}
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
System.out.println("afterTestMethod " + testContext.toString());
}
@Override
public void afterTestClass(TestContext testContext) throws Exception {
System.out.println("afterTestClass " + testContext.toString());
}
}
public static class MyListener2 implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println("ContextRefreshedEvent " + event.toString());
}
}
@Configuration
public static class _Config {
@Bean
public Bean1 bean1() {
return new Bean1();
}
@Bean
public Bean2 bean2() {
return new Bean2();
}
@Bean
public MyListener1 myListener1() {
return new MyListener1();
}
@Bean
public MyListener2 myListener2() {
return new MyListener2();
}
}
@Test
public void test1() {
System.out.println("test1()");
}
@Test
public void test2() {
System.out.println("test2()");
}
}
为什么会有这样的设计差异?
有没有可以监听测试的bean?
最佳答案
ApplicationContext
,bean 的容器,只知道如何生成和公开 beans。这或多或少是其功能的限制。它对测试或测试环境一无所知。
ApplicationListener
可以声明为一个 bean,因为 ApplicationContext
定义了监听器可以观察到的生命周期中的各个阶段(无论其使用在何处)。
TestExecutionListener
仅在运行测试的上下文中有用。这与 ApplicationContext
所做的任何事情都没有关系。换句话说,只有 SpringJUnit4ClassRunner
关心这些监听器,因为它运行测试方法。
实际上,TestExecutionListener
bean 可能已由 SpringJUnit4ClassRunner
从 ApplicationContext
中提取。就我而言,这是一个关注点分离的问题。
关于java - 为什么 TestExecutionListener 不能作为 bean 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32552846/