首页 > 文章列表 > Java之Spring整合Junit的方法是什么

Java之Spring整合Junit的方法是什么

java spring junit
168 2023-05-03

Java之Spring整合Junit的方法是什么

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

    1.1 问题

    • 在测试类中,每个测试方法都有以下两行代码:

      • ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");

      • IAccountService as = ac.getBean("accountService",IAccountService.class);

    • 这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。

    1.2 解决思路分析

    • 针对上述问题,需要的是程序能自动创建容器

    • junit无法知晓是否使用了 spring 框架,无法创建 spring 容器了,但junit 暴露了一个注解,可以替换掉它的运行器。

    • 需要依靠 spring 框架提供的运行器,可以读取配置文件(或注解)来创建容器,只需要告诉它配置文件在哪就行了。

    2 配置步骤

    2.1 第一步:拷贝整合 junit 的必备 jar 包到 lib 目录

    • 此处需要注意的是,导入 jar 包时,需要导入一个 spring 中 aop 的 jar 包。

    2.2 第二步:使用@RunWith 注解替换原有运行器

    @RunWith(SpringJUnit4ClassRunner.class)
    
    public class AccountServiceTest {
    
    }

    2.3 第三步:使用@ContextConfiguration 指定 spring 配置文件的位置

    @RunWith(SpringJUnit4ClassRunner.class)
    
    @ContextConfiguration(locations= {"classpath:bean.xml"})
    
    public class AccountServiceTest {
    
    }
    • @ContextConfiguration 注解:

      • locations 属性:用于指定配置文件的位置。如果是类路径下,需要用 classpath:表明

      • classes 属性:用于指定注解的类。当不使用 xml 配置时,需要用此属性指定注解类的位置。

     2.4 第四步:使用@Autowired 给测试类中的变量注入数据

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

    3 不把测试类配到 xml 中的原因

    • 第一:当在 xml 中配置了一个 bean,spring 加载配置文件创建容器时,就会创建对象。

    • 第二:测试类只是在测试功能时使用,而在项目中它并不参与程序逻辑,也不会解决需求上的问题,所以创建完了,并没有使用。那么存在容器中就会造成资源的浪费。