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. 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.
which may mean, that for each @Test
method the context should be initialized again. This is also confirmed in this answer: 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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.