java test 少依赖_我爱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。

org.springframework

spring-context

5.0.2.RELEASE注意版本要与spring-test的版本一致

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

junit

junit

4.12

test

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

org.springframework

spring-test

5.0.2.RELEASE注意版本要与spring-context的版本一致,不一致会报错。

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

/*** 测试类

*@author少年攻城狮

* @Version 1.0*/@RunWith(SpringJUnit4ClassRunner.class)public classAccountServiceTest {

}

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

/*** 测试类

*@author少年攻城狮

* @Version 1.0*/@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations= {"classpath:bean.xml"})public classAccountServiceTest {

}

@ContextConfiguration 注解:

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

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

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

/*** 测试类

*@author少年攻城狮

* @Version 1.0*/@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations= {"classpath:bean.xml"})public classAccountServiceTest {

@AutowiredprivateIAccountService as ;

}

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

在解释这个问题之前,先解除大家的疑虑,配到 XML 中能不能用呢?

答案是肯定的,没问题,可以使用。

那么为什么不采用配置到 xml 中的方式呢?

这个原因是这样的:

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

第二:测试类只是我们在测试功能时使用,而在项目中它并不参与程序逻辑,也不会解决需求上的问

题,所以创建完了,并没有使用。那么存在容器中就会造成资源的浪费。

所以,基于以上两点,我们不应该把测试配置到 xml 文件中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值