(1)导junit的jar坐标
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.2.RELEASE</version> </dependency>
(2)使用junit提供的一个注解把原有的main方法替换,替换成spring提供的
@Runwith:在测试类上进行注解
@RunWith(SpringJUnit4ClassRunner.class)
(3)告知spring的运行器,spring的ioc创建是基于xml还是注解,并且说明位置
@ContextConfiguration
locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
classes:指定注解类所在地位置
@ContextConfiguration(classes = SpringConfigration.class)
@ContextConfiguration(classpath = “classpath:bean.xml”)
当使用spring5.x版本的时候,要求junit的jar必须是4.1.2及以上
(Caused by: java.lang.IllegalStateException: SpringJUnit4ClassRunner requires JUnit 4.12 or higher.)
(4)
@Autowired private ApplicationContext ac;
下面的就不用写了:
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfigration.class);
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");