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

How many times should SpringJUnit4ClassRunner initialize it's context?

said in manual,即

The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case. To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method. Any exceptions thrown by the test will be reported by JUnit as a failure. If no exceptions are thrown, the test is assumed to have succeeded.

这可能意味着,对于每个 @Test 方法,上下文都应该再次初始化。这个答案也证实了这一点:

同时,我在实验中看到了相反的结果:

@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");
    }


}

这段代码输出

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

这可能意味着,在第二次测试之前,上下文没有第二次初始化。

什么是实际和正确的行为以及如何控制它?

如果你想在测试方法之间重新加载Spring上下文,你需要使用@DirtiesContext注解:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/annotation/DirtiesContext.html