Junit 测试之 Spring Test

本文介绍在Spring框架中整合Junit4进行单元测试的方法,解决传统JUnit测试中的Spring容器重复初始化、硬编码获取Bean及数据库操作后遗症等问题。通过使用Spring测试套件,实现高效、自动化的测试过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在做spring相关测试时比较麻烦,如果只用JUnit测试,需要没测有初始化一下applicationContext,效率比较底下,而且也有不足之处。

  1. 导致多次Spring容器初始化问题
    根据JUnit测试方法的调用流程,每执行一个测试方法都会创建一个测试用例的实例并调用setUp()方法。由于一般情况下,我们在setUp()方法 中初始化Spring容器,这意味着如果测试用例有多少个测试方法,Spring容器就会被重复初始化多次。虽然初始化Spring容器的速度并不会太 慢,但由于可能会在Spring容器初始化时执行加载Hibernate映射文件等耗时的操作,如果每执行一个测试方法都必须重复初始化Spring容 器,则对测试性能的影响是不容忽视的;使用Spring测试套件,Spring容器只会初始化一次!

  2. 需要使用硬编码方式手工获取Bean
    在测试用例类中我们需要通过ctx.getBean()方法从Spirng容器中获取需要测试的目标Bean,并且还要进行强制类型转换的造型操作。这种乏味的操作迷漫在测试用例的代码中,让人觉得烦琐不堪;使用Spring测试套件,测试用例类中的属性会被自动填充Spring容器的对应Bean,无须在手工设置Bean!

  3. 数据库现场容易遭受破坏
    测试方法对数据库的更改操作会持久化到数据库中。虽然是针对开发数据库进行操作,但如果数据操作的影响是持久的,可能会影响到后面的测试行为。举个例子, 用户在测试方法中插入一条ID为1的User记录,第一次运行不会有问题,第二次运行时,就会因为主键冲突而导致测试用例失败。所以应该既能够完成功能逻 辑检查,又能够在测试完成后恢复现场,不会留下“后遗症”;使用Spring测试套件,Spring会在你验证后,自动回滚对数据库的操作,保证数据库的现场不被破坏,因此重复测试不会发生问题!

  4. 不方便对数据操作正确性进行检查
    假如我们向登录日志表插入了一条成功登录日志,可是我们却没有对t_login_log表中是否确实添加了一条记录进行检查。一般情况下,我们可能是打开 数据库,肉眼观察  是否插入了相应的记录,但这严重违背了自动测试的原则。试想在测试包括成千上万个数据操作行为的程序时,如何用肉眼进行检查?
    只要你继承Spring的测试套件的用例类,你就可以通过jdbcTemplate在同一事务中访问数据库,查询数据的变化,验证操作的正确性!

1. maven 配置

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.12</version>
    <scope>test</scope>
</dependency>

2.创建BaseJunit4Test基类

创建 Spring Test 的基类,该类主要用来加载配置文件,设置web环境。
所有的测试类,都继承该类即可。

import org.junit.runner.RunWith;  
import org.springframework.test.context.ContextConfiguration;  
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;  
  
@RunWith(SpringJUnit4ClassRunner.class) //使用junit4进行测试  
@ContextConfiguration(locations={"classpath:spring.xml","classpath:spring-mvc.xml","classpath:spring-hibernate.xml","classpath:spring-ehcache.xml"}) //加载配置文件
@WebAppConfiguration("src/main/webapp")
//------------如果加入以下代码,所有继承该类的测试类都会遵循该配置,也可以不加,在测试类的方法上///控制事务,参见下一个实例    
//这个非常关键,如果不加入这个注解配置,事务控制就会完全失效!    
//@Transactional    
//这里的事务关联到配置文件中的事务控制器(transactionManager = "transactionManager"),同时//指定自动回滚(defaultRollback = true)。这样做操作的数据才不会污染数据库!    
//@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)    
//------------    
public class BaseJunit4Test{  
      
}
  1. @RunWith(SpringJUnit4ClassRunner.class) 使用junit4进行测试
  2. @ContextConfiguration() 加载spring相关的配置文件
  3. @WebAppConfiguration() 设置web项目的环境,如果是Web项目,必须配置该属性,否则无法获取 web 容器相关的信息(request、context 等信息)

3.测试类

import org.junit.Test;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.test.annotation.Rollback;  
import org.springframework.transaction.annotation.Transactional;  
  
import cn.com.infcn.ade.service.UserManagerService;
import cn.com.infcn.model.pmodel.AdeUser;  
  
public class UserTest extends BaseJunit4Test{  
    @Autowired //自动注入  
    private UserManagerService userManagerService;  
      
    @Test  
    @Transactional   //标明此方法需使用事务    
    @Rollback(false)  //标明使用完此方法后事务不回滚,true时为回滚   
    public void testUser(){  
        System.out.println("测试Spring整合Junit4进行单元测试");  
          
        AdeUser user = userManagerService.get("0");
        System.out.println(user);
        System.out.println("------------"+user.getLoginName());
    }
}  
  1. 使用Spring Test 可以使用@Autowired 自动注入 相关的bean信息,而不需要自己手动通过getBean去获取相应的bean信息。
  2. @Transaction
    使用Spring Test 测试,可以 @Transaction 注解,表示该方法使用spring的事务。
  3. @Rollback(false)
    标明使用完此方法后事务不回滚,true时为回滚。
    比如每次打包或提交时,都执行下所有的测试类,而测试类每次都进行插入或删除数据或导致数据库中的数据不完整,为了防止执行测试类都修改库中的数据,可以设置Rollback(true)。



作者:jijs
链接:https://www.jianshu.com/p/00bc74a78d33
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

微信小程序提供了日期时间选择器组件`picker`和日历组件`calendar`,但如果需要自定义样式或者功能,可以考虑封装一个日期时间组件。 以下是一个简单的日期时间组件的封装示例: 1. 在`/components`目录下创建一个`datetime-picker`文件夹,创建`datetime-picker.wxml`、`datetime-picker.wxss`、`datetime-picker.js`和`datetime-picker.json`四个文件。 2. 在`datetime-picker.json`中定义组件的属性: ```json { "component": true, "usingComponents": {}, "properties": { "startDate": { "type": String, "value": "2023-02-15", }, "endDate": { "type": String, "value": "2023-02-20", }, "startTime": { "type": String, "value": "00:00", }, "endTime": { "type": String, "value": "23:59", }, "defaultDate": { "type": String, "value": "", }, "defaultTime": { "type": String, "value": "", }, "format": { "type": String, "value": "datetime", }, "showTime": { "type": Boolean, "value": true, }, "showDate": { "type": Boolean, "value": true, }, "startPlaceholder": { "type": String, "value": "开始时间", }, "endPlaceholder": { "type": String, "value": "结束时间", }, "bind:change": { "type": Function, "value": "", } }, "options": { "styleIsolation": "apply-shared" } } ``` 上述属性中: - `startDate`和`endDate`为日期范围,用于限制可选日期的范围; - `startTime`和`endTime`为时间范围,用于限制可选时间的范围; - `defaultDate`和`defaultTime`为默认值; - `format`为显示格式,支持`datetime`、`date`和`time`三种格式; - `showTime`和`showDate`分别控制是否显示时间和日期选择器; - `startPlaceholder`和`endPlaceholder`为开始时间和结束时间的占位符; - `bind:change`为选择器值变化时的回调函数。 3. 在`datetime-picker.wxml`中定义选择器组件: ```html <view class="datetime-picker"> <view wx:if="{{showDate}}" class="datetime-picker-item"> <picker mode="date" start="{{startDate}}" end="{{endDate}}" value="{{selectedDate}}" bindchange="onDateChange"> <view class="datetime-picker-value"> <text wx:if="{{selectedDate}}">{{selectedDate}}</text> <text wx:else>{{startPlaceholder}}</text> </view> </picker> </view> <view wx:if="{{showTime}}" class="datetime-picker-item"> <picker mode="time" start="{{startTime}}" end="{{endTime}}" value="{{selectedTime}}" bindchange="onTimeChange"> <view class="datetime-picker-value"> <text wx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值