Spring 整合 Junit
* 问题
在测试类中,每个测试方法都有以下两行代码:
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);
这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。
注意:
当我们使用spring 5.x版本的时候,要求junit的jar必须是4.12及以上
1 第一步:拷贝整合 junit 的必备 jar 包到 lib 目录
第一种: 导入 jar 包时,需要导入一个 spring 中 aop 的 jar 包。
第二种:
<dependency>
<groupId>org.spingframework</groupId>
<artifactId>sping-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
2 第二步:使用@RunWith 注解替换原有运行器
@RunWith(SpringJUnit4ClassRunner.class)
public class AccountServiceTest {
}
3 第三步:使用@ContextConfiguration 指定 spring 配置文件的位置
* 使用xml文件配置
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
}
* 使用纯注解配置
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = "SpingConfiguration.class")
public class AccountServiceTest {
}
@ContextConfiguration 注解:
locations属性:用于指定配置文件的位置。如果是类路径下,需要用 classpath:表明
classes属性:用于指定注解的类。当不使用 xml 配置时,需要用此属性指定注解类的位置。
4 第四步:使用@Autowired 给测试类中的变量注入数据
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
@Autowired
private IAccountService as ;
}