Junit使用教程(四)

释放双眼,带上耳机,听听看~!

一、会用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)基本用法

  1. package

 com.test;  

  1.   
  2. import

 javax.annotation.Resource;  

  1.   
  2. import

 org.junit.Test;  

  1. import

 org.junit.runner.RunWith;  

  1. import

 org.springframework.test.context.ContextConfiguration;  

  1. import

 org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  

  1.   
  2. @RunWith

(SpringJUnit4ClassRunner.
class
)  

  1. @ContextConfiguration

(locations = { 
"classpath:config/applicationContext-*.xml"

"classpath:services/ext/service-*.xml"
 })  

  1. public

 
class
 UserServiceTest {  

  1.   
  2.     

@Resource
  

  1.     

private
 IUserService userService;  

  1.   
  2.     

@Test
  

  1.     

public
 
void
 testAddOpinion1() {  

  1.         userService.downloadCount(

1
);  

  1.         System.out.println(

1
);  

  1.     }  
  2.   
  3.     

@Test
  

  1.     

public
 
void
 testAddOpinion2() {  

  1.         userService.downloadCount(

2
);  

  1.         System.out.println(

2
);  

  1.     }  
  2. }  

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

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

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

2)事务用法

  1. package

 com.test;  

  1.   
  2. import

 javax.annotation.Resource;  

  1.   
  2. import

 org.junit.Test;  

  1. import

 org.junit.runner.RunWith;  

  1. import

 org.springframework.test.annotation.Rollback;  

  1. import

 org.springframework.test.context.ContextConfiguration;  

  1. import

 org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  

  1. import

 org.springframework.test.context.transaction.TransactionConfiguration;  

  1. import

 org.springframework.transaction.annotation.Transactional;  

  1.   
  2. @RunWith

(SpringJUnit4ClassRunner.
class
)  

  1. @ContextConfiguration

(locations = { 
"classpath:config/applicationContext-*.xml"

"classpath:services/ext/service-*.xml"
 })  

  1. @Transactional

  

  1. @TransactionConfiguration

(transactionManager = 
"transactionManager"
)  

  1. //@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)

  

  1. public

 
class
 UserServiceTest {  

  1.   
  2.     

@Resource
  

  1.     

private
 IUserService userService;  

  1.   
  2.     

@Test
  

  1. //  @Transactional

  

  1.     

public
 
void
 testAddOpinion1() {  

  1.         userService.downloadCount(

1
);  

  1.         System.out.println(

1
);  

  1.     }  
  2.   
  3.     

@Test
  

  1.     

@Rollback
(
false
)  

  1.     

public
 
void
 testAddOpinion2() {  

  1.         userService.downloadCount(

2
);  

  1.         System.out.println(

2
);  

  1.     }  
  2. }  

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

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

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

3)继承AbstractTransactionalJUnit4SpringContextTests

  1. package

 com.test;  

  1.   
  2. import

 javax.annotation.Resource;  

  1.   
  2. import

 org.junit.Test;  

  1. import

 org.springframework.test.context.ContextConfiguration;  

  1. import

 org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;  

  1. import

 org.springframework.test.context.transaction.TransactionConfiguration;  

  1.   
  2. @ContextConfiguration

(locations = { 
"classpath:config/applicationContext-*.xml"

"classpath:services/ext/service-*.xml"
 })  

  1. @TransactionConfiguration

(transactionManager = 
"transactionManager"
, defaultRollback = 
false
)  

  1. public

 
class
 UserServiceTest 
extends
 AbstractTransactionalJUnit4SpringContextTests {  

  1.   
  2.     

@Resource
  

  1.     

private
 IUserService userService;  

  1.   
  2.     

@Test
  

  1.     

public
 
void
 testAddOpinion1() {  

  1.         userService.downloadCount(

1
);  

  1.         System.out.println(

1
);  

  1.     }  
  2.   
  3.     

@Test
  

  1.     

public
 
void
 testAddOpinion2() {  

  1.         userService.downloadCount(

2
);  

  1.         System.out.println(

2
);  

  1.     }  
  2. }  

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

4)继承

  1. package

 com.test;  

  1.   
  2. import

 org.springframework.test.context.ContextConfiguration;  

  1. import

 org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;  

  1. import

 org.springframework.test.context.transaction.TransactionConfiguration;  

  1.   
  2. @ContextConfiguration

(locations = { 
"classpath:config/applicationContext-*.xml"

"classpath:services/ext/service-*.xml"
 })  

  1. @TransactionConfiguration

(transactionManager = 
"transactionManager"
)  

  1. public

 
class
 BaseTestCase 
extends
 AbstractTransactionalJUnit4SpringContextTests {  

  1.   

  2. }  

  3. package

 com.test;  

  1.   
  2. import

 javax.annotation.Resource;  

  1.   
  2. import

 org.junit.Test;  

  1. import

 org.springframework.test.annotation.Rollback;  

  1.   
  2. public

 
class
 UserServiceTest 
extends
 BaseTestCase {  

  1.   
  2.     

@Resource
  

  1.     

private
 IUserService userService;  

  1.   
  2.     

@Test
  

  1.     

public
 
void
 testAddOpinion1() {  

  1.         userService.downloadCount(

1
);  

  1.         System.out.println(

1
);  

  1.     }  
  2.   
  3.     

@Test
  

  1.     

@Rollback
(
false
)  

  1.     

public
 
void
 testAddOpinion2() {  

  1.         userService.downloadCount(

2
);  

  1.         System.out.println(

2
);  

  1.     }  
  2. }  

5)综合

  1. @RunWith

(SpringJUnit4ClassRunner.
class
)  

  1. @ContextConfiguration

  

  1. @TransactionConfiguration

  

  1. @Transactional

  

  1. public

 
class
 PersonDaoTransactionUnitTest 
extends
 AbstractTransactionalJUnit4SpringContextTests {  

  1.   
  2.     

final
 Logger logger = LoggerFactory.getLogger(PersonDaoTransactionUnitTest.
class
);  

  1.   
  2.     

protected
 
static
 
int
 SIZE = 
2
;  

  1.     

protected
 
static
 Integer ID = 
new
 Integer(
1
);  

  1.     

protected
 
static
 String FIRST_NAME = 
"Joe"
;  

  1.     

protected
 
static
 String LAST_NAME = 
"Smith"
;  

  1.     

protected
 
static
 String CHANGED_LAST_NAME = 
"Jackson"
;  

  1.   
  2.     

@Autowired
  

  1.     

protected
 PersonDao personDao = 
null
;  

  1.   
  2.     

/** 

  1.      * Tests that the size and first record match what is expected before the transaction. 
  2.      */

  

  1.     

@BeforeTransaction
  

  1.     

public
 
void
 beforeTransaction() {  

  1.         testPerson(

true
, LAST_NAME);  

  1.     }  
  2.   
  3.     

/** 

  1.      * Tests person table and changes the first records last name. 
  2.      */

  

  1.     

@Test
  

  1.     

public
 
void
 testHibernateTemplate() 
throws
 SQLException {  

  1.         assertNotNull(

"Person DAO is null."
, personDao);  

  1.   
  2.         Collection<Person> lPersons = personDao.findPersons();  
  3.   
  4.         assertNotNull(

"Person list is null."
, lPersons);  

  1.         assertEquals(

"Number of persons should be "
 + SIZE + 
"."
, SIZE, lPersons.size());  

  1.   
  2.         

for
 (Person person : lPersons) {  

  1.             assertNotNull(

"Person is null."
, person);  

  1.   
  2.             

if
 (ID.equals(person.getId())) {  

  1.                 assertEquals(

"Person first name should be "
 + FIRST_NAME + 
"."
, FIRST_NAME, person.getFirstName());  

  1.                 assertEquals(

"Person last name should be "
 + LAST_NAME + 
"."
, LAST_NAME, person.getLastName());  

  1.   
  2.                 person.setLastName(CHANGED_LAST_NAME);  
  3.   
  4.                 personDao.save(person);  
  5.             }  
  6.         }  
  7.     }  
  8.   
  9.     

/** 

  1.      * Tests that the size and first record match what is expected after the transaction. 
  2.      */

  

  1.     

@AfterTransaction
  

  1.     

public
 
void
 afterTransaction() {  

  1.         testPerson(

false
, LAST_NAME);  

  1.     }  
  2.   
  3.     

/** 

  1.      * Tests person table. 
  2.      */

  

  1.     

protected
 
void
 testPerson(
boolean
 beforeTransaction, String matchLastName) {  

  1.         List<Map<String, Object>> lPersonMaps = simpleJdbcTemplate.queryForList(

"SELECT * FROM PERSON"
);  

  1.   
  2.         assertNotNull(

"Person list is null."
, lPersonMaps);  

  1.         assertEquals(

"Number of persons should be "
 + SIZE + 
"."
, SIZE, lPersonMaps.size());  

  1.   
  2.         Map<String, Object> hPerson = lPersonMaps.get(

0
);  

  1.   
  2.         logger.debug((beforeTransaction ? 

"Before"
 : 
"After"
) + 
" transaction.  "
 + hPerson.toString());  

  1.   
  2.         Integer id = (Integer) hPerson.get(

"ID"
);  

  1.         String firstName = (String) hPerson.get(

"FIRST_NAME"
);  

  1.         String lastName = (String) hPerson.get(

"LAST_NAME"
);  

  1.   
  2.         

if
 (ID.equals(id)) {  

  1.             assertEquals(

"Person first name should be "
 + FIRST_NAME + 
"."
, FIRST_NAME, firstName);  

  1.             assertEquals(

"Person last name should be "
 + matchLastName + 
"."
, matchLastName, lastName);  

  1.         }  
  2.     }  
  3.   
  4. }  

@BeforeTransaction在事务之前执行

@AfterTransaction在事务之后执行

@NotTransactional不开启事务

 

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

给TA打赏
共{{data.count}}人
人已打赏
安全经验

职场中的那些话那些事

2021-9-24 20:41:29

安全经验

Mysql 慢查询和慢查询日志分析

2021-11-28 16:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索