Spring框架整合Junit单元测试框架的必要:
正规的开发方式是将业务层和持久层称为服务器端,将web控制层 分离出来。
写服务器端的人和写前端WEB控制层的人最后要将代码进行整合。
那么写服务器端的人要对他自己写的业务层和持久层代码进行测试。就得用到单元测试框架。
如果不进行测试,服务器端代码有错误。前端和服务器进行整合,出现了错误。那么,写前端的人会认为是前端代码出现的错误 。实则是服务器端代码有错误。
实际正规开发中
一般先写业务层的接口(有哪些业务是固定的),再写业务层的实现类。
再写持久层的接口和实现类。
再进行真正的测试。
整合单元测试框架的目的是为了测试更加简单。
整合单元测试框架的步骤
1、 导入jar包
2、 创建配置文件applicationContext.xml’
3、 将资源交给Spring框架去管理。可以是注解方式也可以是配置文件方式。
4、 在测试类上添加@RunWith和@ContextConfiguration注解
@RunWith(SpringJUnit4ClassRunner.class)//替换原来的运行器
@ContextConfiguration(locations={"classpath:applicationContext.xml"})//指定Spring配置文件的位置。Classpath必须写。不写找不到配置文件。
5、 使用注入注解来给成员属性注入值
@Autowired
@Resource
@Value
废话不多说,直接上代码
持久层代码
class CustomerDaoImplimplements CustomerDao{
@Override
public void save() {
System.out.println("--持久层保存了..");
}
}
业务层代码
public class CustomerServiceImpl implements CustomerService {
//依赖注入————set方式,提供set方法
private CustomerDaocustomerDao;
public void setCustomerDao(CustomerDao customerDao) {
this.customerDao =customerDao;
}
public void save() {
System.out.println("--业务层保存..");
customerDao.save();
}
}
整合单元测试框架代码
/*
* Spring框架整合单元测试框架
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class TestDemo {
//注解方式的依赖注入
@Resource(name="customerService")
private CustomerServicecustomerService;
@Test
public void fun() {
customerService.save();
}
}
配置文件
<!-- 开启注解的扫描 -->
<context:component-scanbase-package="com.itheima"/>
<!-- 将资源交给Spring框架的IOC容器去管理 -->
<beanid="customerDao"class="com.itheima.dao.impl.CustomerDaoImpl"></bean>
<beanid="customerService"class="com.itheima.service.impl.CustomerServiceImpl">
<!-- 依赖注入 -->
<propertyname="customerDao"ref="customerDao"/>
</bean>
为什么不把测试类配到xml中?
首先,测试类是可以配置到xml中的。
为什么不配到xml中呢?
原因有两个:
1、 当我们在xml中配置一个bean后,Spring框架加载配置文件创建容器的时候,会帮我们创建出该对象。但是我们用不到该对象。
2、 测试类只是我们测试功能用的,并不参与程序逻辑。
所以,就算配置到xml中创建完了,并没有使用,那么在容器中就会造成资源浪费。