为什么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的容器,只知道如何生成和公开bean。那或多或少是它功能的极限。它对测试或测试环境一无所知。

可以将ApplicationListener声明为Bean,因为ApplicationContext在其生命周期中定义了侦听者可以观察到的各个阶段(无论使用哪个位置)。

但是,TestExecutionListener仅在运行测试的上下文中有用。这与ApplicationContext无关。换句话说,只有SpringJUnit4ClassRunner在运行测试方法时才关心这些侦听器。

实际上,TestExecutionListener可能是ApplicationContextSpringJUnit4ClassRunner中提取的。就我而言,这是关注点分离的问题。

09-26 05:47