我爱Java系列---【 Spring 整合 Junit : Spring-test】

目的:

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

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

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

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

所以用在pom.xml文件中导入spring-test依赖,可以把这两句话封装到spring框架中,方便我们之后的调用。

步骤:

1.在pom.xml文件中导入spring-context。

  <!-- spring框架 -->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.2.RELEASE</version>注意版本要与spring-test的版本一致
  </dependency>

2.在pom.xml文件中导入junit。

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version><!--此处需要注意的是,spring5 及以上版本要求 junit 的版本必须是 4.12 及以上,否则用不了-->
      <scope>test</scope>
    </dependency>

 

3.在pom.xml文件中导入 spring 整合 Junit 的坐标----spring-test。

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-test</artifactId>
 <version>5.0.2.RELEASE</version>注意版本要与spring-context的版本一致,不一致会报错。
 </dependency>

4.使用@RunWith 注解替换原有运行器

/**
* 测试类
* @author 少年攻城狮
* @Version 1.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
public class AccountServiceTest {
}

5.使用@ContextConfiguration 指定 spring 配置文件的位置

/**
* 测试类
* @author 少年攻城狮
* @Version 1.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
}
@ContextConfiguration 注解:
locations 属性:用于指定配置文件的位置。如果是类路径下,需要用 classpath:表明

classes 属性:用于指定注解的类。当不使用 xml 配置时,需要用此属性指定注解类的位置,格式: @ContextConfig(classes=Config.class)。

6.使用@Autowired 给测试类中的变量注入数据

/**
* 测试类
* @author 少年攻城狮
* @Version 1.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
@Autowired
private IAccountService as ;
}

问题:为什么不把测试类配到 xml 中?

在解释这个问题之前,先解除大家的疑虑,配到 XML 中能不能用呢?
答案是肯定的,没问题,可以使用。
那么为什么不采用配置到 xml 中的方式呢?
这个原因是这样的:
第一:当我们在 xml 中配置了一个 bean,spring 加载配置文件创建容器时,就会创建对象。
第二:测试类只是我们在测试功能时使用,而在项目中它并不参与程序逻辑,也不会解决需求上的问
题,所以创建完了,并没有使用。那么存在容器中就会造成资源的浪费。
所以,基于以上两点,我们不应该把测试配置到 xml 文件中。

猜你喜欢

转载自www.cnblogs.com/hujunwei/p/11115744.html
今日推荐