九点钟☆方向

记录成长点滴

欢迎来到我的个人博客~


Spring笔记(六) Spring整合Junit

目录

测试类中的问题和解决思路

在测试类中,每个测试方法都有以下两行代码: ApplicationContext ac = new ClassPathXmlApplicationContext(“bean.xml”); IAccountService as = ac.getBean(“accountService”,IAccountService.class); 这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。

解决思路分析

针对上述问题,我们需要的是程序能自动帮我们创建容器。一旦程序能自动为我们创建 spring 容器,我们就 无须手动创建了,问题也就解决了 。我们知道:

  1. 应用程序的入口是main方法
  2. Junit没有main方法也能执行,是因为Junit集成了一个main方法,该方法会判断当前测试类中哪些方法有@Test注解,会让这些方法执行
  3. Junit不会管我们是否采用了Spring框架,因为执行测试方法时,Junit根本不知道我们是否使用了Spring,所以也就不会为我们读取配置文件或配置类,从而创建Spring核心容器。
  4. 由以上三点可知,当测试方法执行时,没有IOC容器,就算用了@Autowired注解也无法实现注入

解决步骤

  1. 导入Spring整合Junit的依赖(Spring-test)和Junit依赖
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.8.RELEASE</version>
</dependency>
<!--当我们使用Spring5.X版本时,Junit的版本必须在4.12以上-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
</dependency>
  1. 使用Junit的@RunWith注解把原有的运行器 main方法替换成Spring提供的

    @RunWith(SpringJUnit4ClassRunner.class)

    @RunWith(SpringJUnit4ClassRunner.class)
    	public class MyTest {  }
    
  2. 使用@ContextConfiguration 指定 spring 配置文件的位置

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = SpringConfig.class)//使用注解类
    //@ContextConfiguration(locations= {"classpath:bean.xml"})  使用xml配置文件
    public class MyTest {   }
       
    @ContextConfiguration 注解
    locations 属性 用于指定配置文件的位置如果是类路径下需要用 classpath:表明
    classes 属性 用于指定注解的类当不使用 xml 配置时需要用此属性指定注解类的位置
    
  3. 使用@Autowired 给测试类中的变量注入数据

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations= {"classpath:bean.xml"})
    public class MyTest {
        @Autowired
        private IAccountService as ;
    }
    

附录(完整代码)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)  //使用注解类
//@ContextConfiguration(locations = "classpath:bean.xml")  使用xml配置文件
public class MyTest {
    @Autowired
    private IAccountService accountService;

    @Test
    public void test1() {
        List<Account> accounts = accountService.findAllAccount();
        for(Account account:accounts) {
            System.out.println(account);
        }
    }
}

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦