1、问题分析
1)应用程序的入口:main方法
2)junit单元测试中,没有main方法也能执行
a.junit集成了一个main方法
b.该方法就会判断当前测试类中哪些方法有@Test注解
c.junit就让有@Test注解的方法执行
3)junit不会管是否采用spring框架
a.在执行方法时,junit根本不知道当前是不是使用了spring框架
b.所以也就不会读取配置文件/配置类创建spring核心容器
4)有以上三点可知
a.当测试方法执行时,没有Ioc容器,就算写了Autowired注解,也无法实现注入
2、Spring整合Junit的配置
1)导入spring整合junit的jar(坐标)
2)使用junit提供的一个注解把原有的main方法替换了,替换成spring提供的@RunWith注解
3)告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置
a.@ContextConfiguration
i.locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
ii.classes:指定注解类所在的位置
3、示例代码:
- /**
- * 使用Junit单元测试:测试配置
- * Spring整合Junit的配置
- * 1、导入spring整合junit的jar(坐标)
- * 2、使用junit提供的一个注解把原有的main方法替换了,替换成spring提供的
- * @RunWith
- * 3、告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置
- * ContextConfiguration
- * locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
- * classes:指定注解类所在的位置
- * 使用Spring 5.x版本的时候,要求Junit的jar必须是4.12及以上
- */
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(classes = SpringConfiguration.class)//使用注解配置
- //@ContextConfiguration(locations = "classpath:bean.xml")//使用xml配置文件
- public class AccountServiceTest {
- @Autowired
- private IAccountService as;
- @Test
- public void testFindAll() {
- //3.执行方法
- List<Account> accounts = as.findAll();
- for (Account account : accounts) {
- System.out.println(account);
- }
- }
- @Test
- public void testFindOne() {
- //3.执行方法
- Account account = as.findById(2);
- System.out.println(account);
- }
- @Test
- public void testSave() {
- //3.执行方法
- Account account = new Account();
- account.setName("test anno withoutxml");
- account.setMoney(12345f);
- as.save(account);
- }
- @Test
- public void testUpdate() {
- //3.执行方法
- Account account = as.findById(6);
- account.setMoney(23456f);
- as.update(account);
- }
- @Test
- public void testDelete() {
- //3.执行方法
- as.delete(6);
- }
- }