Junit使用教程(四)

2024-09-06 15:18
文章标签 使用 教程 junit

本文主要是介绍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)基本用法

[java] view plain copy
print ?
  1. package com.test;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.junit.Test;  
  6. import org.junit.runner.RunWith;  
  7. import org.springframework.test.context.ContextConfiguration;  
  8. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  9.   
  10. @RunWith(SpringJUnit4ClassRunner.class)  
  11. @ContextConfiguration(locations = { "classpath:config/applicationContext-*.xml""classpath:services/ext/service-*.xml" })  
  12. public class UserServiceTest {  
  13.   
  14.     @Resource  
  15.     private IUserService userService;  
  16.   
  17.     @Test  
  18.     public void testAddOpinion1() {  
  19.         userService.downloadCount(1);  
  20.         System.out.println(1);  
  21.     }  
  22.   
  23.     @Test  
  24.     public void testAddOpinion2() {  
  25.         userService.downloadCount(2);  
  26.         System.out.println(2);  
  27.     }  
  28. }  
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 {@Resourceprivate IUserService userService;@Testpublic void testAddOpinion1() {userService.downloadCount(1);System.out.println(1);}@Testpublic 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)事务用法

[java] view plain copy
print ?
  1. package com.test;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.junit.Test;  
  6. import org.junit.runner.RunWith;  
  7. import org.springframework.test.annotation.Rollback;  
  8. import org.springframework.test.context.ContextConfiguration;  
  9. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  10. import org.springframework.test.context.transaction.TransactionConfiguration;  
  11. import org.springframework.transaction.annotation.Transactional;  
  12.   
  13. @RunWith(SpringJUnit4ClassRunner.class)  
  14. @ContextConfiguration(locations = { "classpath:config/applicationContext-*.xml""classpath:services/ext/service-*.xml" })  
  15. @Transactional  
  16. @TransactionConfiguration(transactionManager = "transactionManager")  
  17. //@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)  
  18. public class UserServiceTest {  
  19.   
  20.     @Resource  
  21.     private IUserService userService;  
  22.   
  23.     @Test  
  24. //  @Transactional  
  25.     public void testAddOpinion1() {  
  26.         userService.downloadCount(1);  
  27.         System.out.println(1);  
  28.     }  
  29.   
  30.     @Test  
  31.     @Rollback(false)  
  32.     public void testAddOpinion2() {  
  33.         userService.downloadCount(2);  
  34.         System.out.println(2);  
  35.     }  
  36. }  
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 {@Resourceprivate IUserService userService;@Test
//	@Transactionalpublic 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

[java] view plain copy
print ?
  1. package com.test;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.junit.Test;  
  6. import org.springframework.test.context.ContextConfiguration;  
  7. import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;  
  8. import org.springframework.test.context.transaction.TransactionConfiguration;  
  9.   
  10. @ContextConfiguration(locations = { "classpath:config/applicationContext-*.xml""classpath:services/ext/service-*.xml" })  
  11. @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)  
  12. public class UserServiceTest extends AbstractTransactionalJUnit4SpringContextTests {  
  13.   
  14.     @Resource  
  15.     private IUserService userService;  
  16.   
  17.     @Test  
  18.     public void testAddOpinion1() {  
  19.         userService.downloadCount(1);  
  20.         System.out.println(1);  
  21.     }  
  22.   
  23.     @Test  
  24.     public void testAddOpinion2() {  
  25.         userService.downloadCount(2);  
  26.         System.out.println(2);  
  27.     }  
  28. }  
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 {@Resourceprivate IUserService userService;@Testpublic void testAddOpinion1() {userService.downloadCount(1);System.out.println(1);}@Testpublic void testAddOpinion2() {userService.downloadCount(2);System.out.println(2);}
}

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

4)继承

[java] view plain copy
print ?
  1. package com.test;  
  2.   
  3. import org.springframework.test.context.ContextConfiguration;  
  4. import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;  
  5. import org.springframework.test.context.transaction.TransactionConfiguration;  
  6.   
  7. @ContextConfiguration(locations = { "classpath:config/applicationContext-*.xml""classpath:services/ext/service-*.xml" })  
  8. @TransactionConfiguration(transactionManager = "transactionManager")  
  9. public class BaseTestCase extends AbstractTransactionalJUnit4SpringContextTests {  
  10.   
  11. }  
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 {}
[java] view plain copy
print ?
  1. package com.test;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.junit.Test;  
  6. import org.springframework.test.annotation.Rollback;  
  7.   
  8. public class UserServiceTest extends BaseTestCase {  
  9.   
  10.     @Resource  
  11.     private IUserService userService;  
  12.   
  13.     @Test  
  14.     public void testAddOpinion1() {  
  15.         userService.downloadCount(1);  
  16.         System.out.println(1);  
  17.     }  
  18.   
  19.     @Test  
  20.     @Rollback(false)  
  21.     public void testAddOpinion2() {  
  22.         userService.downloadCount(2);  
  23.         System.out.println(2);  
  24.     }  
  25. }  
package com.test;import javax.annotation.Resource;import org.junit.Test;
import org.springframework.test.annotation.Rollback;public class UserServiceTest extends BaseTestCase {@Resourceprivate IUserService userService;@Testpublic void testAddOpinion1() {userService.downloadCount(1);System.out.println(1);}@Test@Rollback(false)public void testAddOpinion2() {userService.downloadCount(2);System.out.println(2);}
}

5)综合

[java] view plain copy
print ?
  1. @RunWith(SpringJUnit4ClassRunner.class)  
  2. @ContextConfiguration  
  3. @TransactionConfiguration  
  4. @Transactional  
  5. public class PersonDaoTransactionUnitTest extends AbstractTransactionalJUnit4SpringContextTests {  
  6.   
  7.     final Logger logger = LoggerFactory.getLogger(PersonDaoTransactionUnitTest.class);  
  8.   
  9.     protected static int SIZE = 2;  
  10.     protected static Integer ID = new Integer(1);  
  11.     protected static String FIRST_NAME = "Joe";  
  12.     protected static String LAST_NAME = "Smith";  
  13.     protected static String CHANGED_LAST_NAME = "Jackson";  
  14.   
  15.     @Autowired  
  16.     protected PersonDao personDao = null;  
  17.   
  18.     /** 
  19.      * Tests that the size and first record match what is expected before the transaction. 
  20.      */  
  21.     @BeforeTransaction  
  22.     public void beforeTransaction() {  
  23.         testPerson(true, LAST_NAME);  
  24.     }  
  25.   
  26.     /** 
  27.      * Tests person table and changes the first records last name. 
  28.      */  
  29.     @Test  
  30.     public void testHibernateTemplate() throws SQLException {  
  31.         assertNotNull("Person DAO is null.", personDao);  
  32.   
  33.         Collection<Person> lPersons = personDao.findPersons();  
  34.   
  35.         assertNotNull("Person list is null.", lPersons);  
  36.         assertEquals("Number of persons should be " + SIZE + ".", SIZE, lPersons.size());  
  37.   
  38.         for (Person person : lPersons) {  
  39.             assertNotNull("Person is null.", person);  
  40.   
  41.             if (ID.equals(person.getId())) {  
  42.                 assertEquals("Person first name should be " + FIRST_NAME + ".", FIRST_NAME, person.getFirstName());  
  43.                 assertEquals("Person last name should be " + LAST_NAME + ".", LAST_NAME, person.getLastName());  
  44.   
  45.                 person.setLastName(CHANGED_LAST_NAME);  
  46.   
  47.                 personDao.save(person);  
  48.             }  
  49.         }  
  50.     }  
  51.   
  52.     /** 
  53.      * Tests that the size and first record match what is expected after the transaction. 
  54.      */  
  55.     @AfterTransaction  
  56.     public void afterTransaction() {  
  57.         testPerson(false, LAST_NAME);  
  58.     }  
  59.   
  60.     /** 
  61.      * Tests person table. 
  62.      */  
  63.     protected void testPerson(boolean beforeTransaction, String matchLastName) {  
  64.         List<Map<String, Object>> lPersonMaps = simpleJdbcTemplate.queryForList("SELECT * FROM PERSON");  
  65.   
  66.         assertNotNull("Person list is null.", lPersonMaps);  
  67.         assertEquals("Number of persons should be " + SIZE + ".", SIZE, lPersonMaps.size());  
  68.   
  69.         Map<String, Object> hPerson = lPersonMaps.get(0);  
  70.   
  71.         logger.debug((beforeTransaction ? "Before" : "After") + " transaction.  " + hPerson.toString());  
  72.   
  73.         Integer id = (Integer) hPerson.get("ID");  
  74.         String firstName = (String) hPerson.get("FIRST_NAME");  
  75.         String lastName = (String) hPerson.get("LAST_NAME");  
  76.   
  77.         if (ID.equals(id)) {  
  78.             assertEquals("Person first name should be " + FIRST_NAME + ".", FIRST_NAME, firstName);  
  79.             assertEquals("Person last name should be " + matchLastName + ".", matchLastName, lastName);  
  80.         }  
  81.     }  
  82.   
  83. }  
@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";@Autowiredprotected PersonDao personDao = null;/*** Tests that the size and first record match what is expected before the transaction.*/@BeforeTransactionpublic void beforeTransaction() {testPerson(true, LAST_NAME);}/*** Tests person table and changes the first records last name.*/@Testpublic 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.*/@AfterTransactionpublic 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使用教程(四)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1142369

相关文章

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是

嵌入式数据库SQLite 3配置使用讲解

《嵌入式数据库SQLite3配置使用讲解》本文强调嵌入式项目中SQLite3数据库的重要性,因其零配置、轻量级、跨平台及事务处理特性,可保障数据溯源与责任明确,详细讲解安装配置、基础语法及SQLit... 目录0、惨痛教训1、SQLite3环境配置(1)、下载安装SQLite库(2)、解压下载的文件(3)、

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图