简体   繁体   English

SpringJUnit4ClassRunner应该初始化上下文多少次?

[英]How many times should SpringJUnit4ClassRunner initialize it's context?

It is said in manual , that 据说

The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case. Test注释告诉JUnit,可以将其附加到的public void方法作为测试用例运行。 To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method. 为了运行该方法,JUnit首先构造一个新的类实例,然后调用带注释的方法。 Any exceptions thrown by the test will be reported by JUnit as a failure. 测试抛出的任何异常将由JUnit报告为失败。 If no exceptions are thrown, the test is assumed to have succeeded. 如果未引发任何异常,则假定测试成功。

which may mean, that for each @Test method the context should be initialized again. 这可能意味着,对于每个@Test方法,应再次初始化上下文。 This is also confirmed in this answer: https://stackoverflow.com/a/1564309/258483 这个答案也证实了这一点: https : //stackoverflow.com/a/1564309/258483

Simultaneously, I see opposite in my experiment: 同时,我在实验中看到了相反的结果:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringJUnit4ClassRunnerDemo._Config.class)
public class SpringJUnit4ClassRunnerDemo {


    public static class Bean1 {
        {
            System.out.println("Bean1 constructor called");
        }
    }

    public static class Bean2 {

        {
            System.out.println("Bean2 constructor called");
        }

        private Bean1 bean1;

        public Bean1 getBean1() {
            return bean1;
        }

        @Autowired
        public void setBean1(Bean1 bean1) {
            this.bean1 = bean1;

            System.out.println("Bean2.bean1 property set");
        }
    }

    @Configuration
    public static class _Config {

        @Bean
        public Bean1 bean1() {
            return new Bean1();
        }

        @Bean
        public Bean2 bean2() {
            return new Bean2();
        }


    }

    @Autowired
    private Bean1 bean1;

    @Autowired
    private Bean2 bean2;


    @Test
    public void testBean1() {

        assertNotNull(bean1);

        System.out.println("testBean1() done");
    }

    @Test
    public void testBean2() {

        assertNotNull(bean2);

        assertSame(bean2.getBean1(), bean1);

        System.out.println("testBean2() done");
    }


}

This code outputs 该代码输出

Bean1 constructor called
Bean2 constructor called
Bean2.bean1 property set
testBean1() done
testBean2() done

which may mean, that context is not initialized second time before second test. 这可能意味着上下文没有在第二次测试之前第二次初始化。

What is actual and correct behavior and how to control it? 什么是实际和正确的行为以及如何控制它?

如果要在测试方法之间重新加载Spring上下文,则需要使用@DirtiesContext批注: https : @DirtiesContext 。 html

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

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