繁体   English   中英

为什么TestExecutionListener不能作为bean工作?

[英]Why TestExecutionListener does not work as a bean?

为什么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在运行测试方法SpringJUnit4ClassRunner关心这些侦听器。

实际上,可以通过SpringJUnit4ClassRunnerApplicationContext提取TestExecutionListener bean。 就我而言,这是关注点分离的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM