一、会用Spring测试套件的好处

在开发基于Spring的应用时,如果你还直接使用Junit进行单元测试,那你就错过了Spring为我们所提供的饕餮大餐了。使用Junit直接进行单元测试有以下四大不足:

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(或Dao等)在同一事务中访问数据库,查询数据的变化,验证操作的正确性!

Spring提供了一套扩展于Junit测试用例的测试套件,使用这套测试套件完全解决了以上四个问题,让我们测试Spring的应用更加方便。这个测试套件主要由org.springframework.test包下的若干类组成,使用简单快捷,方便上手。

二、使用方法

1)基本用法

package com.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:config/applicationContext-*.xml", "classpath:services/ext/service-*.xml" })
public class UserServiceTest { @Resource
private IUserService userService; @Test
public void testAddOpinion1() {
userService.downloadCount(1);
System.out.println(1);
} @Test
public void testAddOpinion2() {
userService.downloadCount(2);
System.out.println(2);
}
}

@RunWith(SpringJUnit4ClassRunner.class) 用于配置spring中测试的环境

@ContextConfiguration(locations = { "classpath:config/applicationContext-*.xml", "classpath:services/ext/service-*.xml" })用于指定配置文件所在的位置

@Resource注入Spring容器Bean对象,注意与@Autowired区别

2)事务用法

package com.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:config/applicationContext-*.xml", "classpath:services/ext/service-*.xml" })
@Transactional
@TransactionConfiguration(transactionManager = "transactionManager")
//@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
public class UserServiceTest { @Resource
private IUserService userService; @Test
// @Transactional
public void testAddOpinion1() {
userService.downloadCount(1);
System.out.println(1);
} @Test
@Rollback(false)
public void testAddOpinion2() {
userService.downloadCount(2);
System.out.println(2);
}
}

@TransactionConfiguration(transactionManager="transactionManager")读取Spring配置文件中名为transactionManager的事务配置,defaultRollback为事务回滚默认设置。该注解是可选的,可使用@Transactional与@Rollback配合完成事务管理。当然也可以使用@Transactional与@TransactionConfiguration配合。

@Transactional开启事务。可放到类或方法上,类上作用于所有方法。

@Rollback事务回滚配置。只能放到方法上。

3)继承AbstractTransactionalJUnit4SpringContextTests

package com.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.transaction.TransactionConfiguration; @ContextConfiguration(locations = { "classpath:config/applicationContext-*.xml", "classpath:services/ext/service-*.xml" })
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
public class UserServiceTest extends AbstractTransactionalJUnit4SpringContextTests { @Resource
private IUserService userService; @Test
public void testAddOpinion1() {
userService.downloadCount(1);
System.out.println(1);
} @Test
public void testAddOpinion2() {
userService.downloadCount(2);
System.out.println(2);
}
}

AbstractTransactionalJUnit4SpringContextTests:这个类为我们解决了在web.xml中配置OpenSessionInview所解决的session生命周期延长的问题,所以要继承这个类。该类已经在类级别预先配置了好了事物支持,因此不必再配置@Transactional和@RunWith

4)继承

package com.test;

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.transaction.TransactionConfiguration; @ContextConfiguration(locations = { "classpath:config/applicationContext-*.xml", "classpath:services/ext/service-*.xml" })
@TransactionConfiguration(transactionManager = "transactionManager")
public class BaseTestCase extends AbstractTransactionalJUnit4SpringContextTests { }
package com.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.springframework.test.annotation.Rollback; public class UserServiceTest extends BaseTestCase { @Resource
private IUserService userService; @Test
public void testAddOpinion1() {
userService.downloadCount(1);
System.out.println(1);
} @Test
@Rollback(false)
public void testAddOpinion2() {
userService.downloadCount(2);
System.out.println(2);
}
}

5)综合

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TransactionConfiguration
@Transactional
public class PersonDaoTransactionUnitTest extends AbstractTransactionalJUnit4SpringContextTests { final Logger logger = LoggerFactory.getLogger(PersonDaoTransactionUnitTest.class); protected static int SIZE = 2;
protected static Integer ID = new Integer(1);
protected static String FIRST_NAME = "Joe";
protected static String LAST_NAME = "Smith";
protected static String CHANGED_LAST_NAME = "Jackson"; @Autowired
protected PersonDao personDao = null; /**
* Tests that the size and first record match what is expected before the transaction.
*/
@BeforeTransaction
public void beforeTransaction() {
testPerson(true, LAST_NAME);
} /**
* Tests person table and changes the first records last name.
*/
@Test
public void testHibernateTemplate() throws SQLException {
assertNotNull("Person DAO is null.", personDao); Collection<Person> lPersons = personDao.findPersons(); assertNotNull("Person list is null.", lPersons);
assertEquals("Number of persons should be " + SIZE + ".", SIZE, lPersons.size()); for (Person person : lPersons) {
assertNotNull("Person is null.", person); if (ID.equals(person.getId())) {
assertEquals("Person first name should be " + FIRST_NAME + ".", FIRST_NAME, person.getFirstName());
assertEquals("Person last name should be " + LAST_NAME + ".", LAST_NAME, person.getLastName()); person.setLastName(CHANGED_LAST_NAME); personDao.save(person);
}
}
} /**
* Tests that the size and first record match what is expected after the transaction.
*/
@AfterTransaction
public void afterTransaction() {
testPerson(false, LAST_NAME);
} /**
* Tests person table.
*/
protected void testPerson(boolean beforeTransaction, String matchLastName) {
List<Map<String, Object>> lPersonMaps = simpleJdbcTemplate.queryForList("SELECT * FROM PERSON"); assertNotNull("Person list is null.", lPersonMaps);
assertEquals("Number of persons should be " + SIZE + ".", SIZE, lPersonMaps.size()); Map<String, Object> hPerson = lPersonMaps.get(0); logger.debug((beforeTransaction ? "Before" : "After") + " transaction. " + hPerson.toString()); Integer id = (Integer) hPerson.get("ID");
String firstName = (String) hPerson.get("FIRST_NAME");
String lastName = (String) hPerson.get("LAST_NAME"); if (ID.equals(id)) {
assertEquals("Person first name should be " + FIRST_NAME + ".", FIRST_NAME, firstName);
assertEquals("Person last name should be " + matchLastName + ".", matchLastName, lastName);
}
} }

@BeforeTransaction在事务之前执行

@AfterTransaction在事务之后执行

@NotTransactional不开启事务

好了,本篇作为Junit补充就说到这里了,希望大家多多分享经验哦。

Junit使用教程(四)的更多相关文章

  1. Junit使用教程(三)

    四.实例总结 1. 参数化测试 有时一个测试方法,不同的参数值会产生不同的结果,那么我们为了测试全面,会把多个参数值都写出来并一一断言测试,这样有时难免费时费力,这是我们便可以采用参数化测试来解决这个 ...

  2. CRL快速开发框架系列教程四(删除数据)

    本系列目录 CRL快速开发框架系列教程一(Code First数据表不需再关心) CRL快速开发框架系列教程二(基于Lambda表达式查询) CRL快速开发框架系列教程三(更新数据) CRL快速开发框 ...

  3. 手把手教从零开始在GitHub上使用Hexo搭建博客教程(四)-使用Travis自动部署Hexo(2)

    前言 前面一篇文章介绍了Travis自动部署Hexo的常规使用教程,也是个人比较推荐的方法. 前文最后也提到了在Windows系统中可能会有一些小问题,为了在Windows系统中也可以实现使用Trav ...

  4. C#微信公众号开发系列教程四(接收普通消息)

    微信公众号开发系列教程一(调试环境部署) 微信公众号开发系列教程一(调试环境部署续:vs远程调试) C#微信公众号开发系列教程二(新手接入指南) C#微信公众号开发系列教程三(消息体签名及加解密) C ...

  5. 无废话ExtJs 入门教程四[表单:FormPanel]

    无废话ExtJs 入门教程四[表单:FormPanel] extjs技术交流,欢迎加群(201926085) 继上一节内容,我们在窗体里加了个表单.如下所示代码区的第28行位置,items:form. ...

  6. TFS(Team Foundation Server)敏捷使用教程(四):工作项跟踪(1)

    工作项跟踪(1) 可跟踪性是软件过程的重要能力,TFS主要是以工作项来实现过程的可跟踪性.曾有人问:"你们实际项目里的工作项是怎么样的?能不能让我们看看?"我也一直很好奇别的公司T ...

  7. Android Studio系列教程四--Gradle基础

    Android Studio系列教程四--Gradle基础 2014 年 12 月 18 日 DevTools 本文为个人原创,欢迎转载,但请务必在明显位置注明出处!http://stormzhang ...

  8. Laravel教程 四:数据库和Eloquent

    Laravel教程 四:数据库和Eloquent 此文章为原创文章,未经同意,禁止转载. Eloquent Database 上一篇写了一些Laravel Blade的基本用法和给视图传递变量的几种方 ...

  9. NGUI系列教程四(自定义Atlas,Font)

    今天我们来看一下怎么自定义NGUIAtlas,制作属于自己风格的UI.第一部分:自定义 Atlas1 . 首先我们要准备一些图标素材,也就是我们的UI素材,将其导入到unity工程中.2. 全选我们需 ...

  10. Qt零基础教程(四) QWidget详解篇

    在博客园里面转载我自己写的关于Qt的基础教程,没次写一篇我会在这里更新一下目录: Qt零基础教程(四) QWidget详解(1):创建一个窗口 Qt零基础教程(四) QWidget详解(2):QWid ...

随机推荐

  1. ASP.NET MVC 学习第二天

    今天使用mvc完成简单的增删改,内容比较简单,来熟悉一下mvc,数据库操作是用前面的ef,也算是温习一下ef吧. 新建mvc项目,在项目中的Models内添加ef,我这里只操作一下简单的user表.里 ...

  2. Java架构师之路:JAVA程序员必看的15本书

    作为Java程序员来说,最痛苦的事情莫过于可以选择的范围太广,可以读的书太多,往往容易无所适从.我想就我自己读过的技术书籍中挑选出来一些,按照学习的先后顺序,推荐给大家,特别是那些想不断提高自己技术水 ...

  3. cocos中BatchNode精灵集合的使用

    1.CCSpriteBatchNode是为了提高渲染效率而实现的,它继承自CCNode 2.fps:帧率,是游戏中衡量流畅度的一个很重要的概念,cocos中默认的帧率是60,即一秒刷新60帧 3.精灵 ...

  4. 团队项目之NABC

    Time:2013-10-22 Author:wang 一个成功的人,总是知道如何管理自己的时间,如何让自己的时间得到最充分最有效的利用.对学生一族而言,课业负担重,各种课程.各种活动.各种社团,如果 ...

  5. bnuoj 33656 J. C.S.I.: P15(图形搜索题)

    http://www.bnuoj.com/bnuoj/problem_show.php?pid=33656 [题解]:暴力搜索题 [code]: #include <iostream> # ...

  6. Ui设计哪里有好的素材

    刚看到花瓣网,的确不错,以后得多逛逛了.(不喷广告,只留作笔记)

  7. android 开发解密时出现pad block corrupted 错误

    情景:在虚拟机上运行正常的,但是到我的真机上就解密失败,出现pad block corrupted  ,据说是版本原因:我机器是小米3 最新版的android  4.2 出现问题的代码: privat ...

  8. git Clone SSL certificate problem: self signed certificate

    自己的git服务器遇到证书是自签的,git验证后会拒绝,此时,采用如下命令临时禁用就好 git -c http.sslVerify=false clone https://domain.com/pat ...

  9. 【WCF--初入江湖】08 并发与实例模式

    08 并发与实例模式 1. 实例上下文模式   一个服务代理:servicePoxy ChannelFactory<IService1> factoryservicel = new Cha ...

  10. Even Fibonacci numbers

    --Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting ...