[jeeplus]jeeplus 中的单元测试方法论

本贴最后更新于 2233 天前,其中的信息可能已经时移世易

[初学者级别]

在刚开始接触 jeeplus 时,就一直纠结怎么用自己之前最开始的单元测试方法,对 dao 层,service 层的方法进行测试。

发现:

  1. Junit 的单元测试在 jeeplus 框架下,使用时会出现需要有 ApplicationContext ,或者需要实现模拟 请求对象等各种问题,但是 jeeplus 中的 SpringContextHolder 自己却不太会用,(或者是环境、jar 包的问题引起各种异常),不能进行常用的单元测试方法。

  2. 刚开始按照在网上找到的一些博文中的方法,也是各种尝试,同样不能解决问题。后来就搁置了好久好久。最近,实在是觉得还是非常有必要调通,会给项目的完成提供很大助力。所以,又开始找了许多博文来试、请教大佬,最终,终于调通了。

  3. 在后续的使用中,还存在着各种问题,比如 Shiro 的权限问题,还需要继续研究。

总结:

(仅简单说下大致的用法,内中详细自己还没掌握透彻,求大佬补充。)

  1. pom.xml 中需要检查是否引用了正确的 jar 包,尤其注意一些环境、jar 包的版本问题。
    另外,需要注意可能还有其他 jar 的问题。
<!-- TEST begin --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId> <version>2.2.4</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>javax.el</artifactId> <version>2.2.4</version> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-websocket</artifactId> <version>7.0.52</version> <scope>test</scope> </dependency> <!-- TEST end -->
  1. 创建单元测试基类
package com.jeeplus.core.junit; 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; /** * Created by pc on 2019/6/3. */ @RunWith(SpringJUnit4ClassRunner.class)//表示整合JUnit4进行测试 @ContextConfiguration(locations={"classpath:spring/spring-context*.xml","classpath:/spring/spring-mvc*.xml"}) @WebAppConfiguration //声明以 web 形式进行测试 public class BaseJunit4Test { }
  1. 使用 Junit 开始单元测试。
    a. 创建的测试类需要继承单元测试基类。
    b. 可以正常使用 Spring 的注解方式注入 service 等。
    c. 需要注意 Jeeplus 中使用的 Shiro 权限控制问题,很多 Jeeplus 框架 中的方法可能有权限控制问题。

eg:

package com.jeeplus.modules.junittest; import com.jeeplus.common.utils.IdGen; import com.jeeplus.common.utils.SpringContextHolder; import com.jeeplus.core.junit.BaseJunit4Test; import com.jeeplus.modules.importxlsx.entity.yifenyiduanbiao.DYifenyiduanbiao; import com.jeeplus.modules.importxlsx.entity.zhuanyexinxibiao.DZhuanyexinxibiao; import com.jeeplus.modules.importxlsx.service.zhuanyexinxibiao.DZhuanyexinxibiaoService; import com.jeeplus.modules.levelformajorsfordetails.entity.LevelForMajorsDetails; import com.jeeplus.modules.levelformajorsfordetails.entity.LevelForMajorsForDetails; import com.jeeplus.modules.levelformajorsfordetails.mapper.LevelForMajorsDetailsMapper; import com.jeeplus.modules.levelformajorsfordetails.service.LevelForMajorsDetailsService; import com.jeeplus.modules.levelformajorsfordetails.service.LevelForMajorsForDetailsService; import com.jeeplus.modules.sys.entity.User; import org.apache.ibatis.annotations.Param; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import javax.persistence.Basic; import java.util.Date; import java.util.List; /** * Created by pc on 2019/6/3. */ public class JunitTestERecode extends BaseJunit4Test{ @Autowired LevelForMajorsDetailsService levelForMajorsDetailsService; @Autowired LevelForMajorsForDetailsService levelForMajorsForDetailsService; @Autowired DZhuanyexinxibiaoService dZhuanyexinxibiaoService; /** * 需要注意的是: * shiro 的权限问题,Service 中大多数查询方法都有权限控制。测试时会遇到 shiro 异常。 */ @Before public void setDate(){ } //测试 LevelForMajorsDetails 中的按更新时间删除记录 @Test public void testDeleteERecord(){ Date date = new Date(); LevelForMajorsDetails levelForMajorsDetails = new LevelForMajorsDetails(); levelForMajorsDetails.setUpdateDate(date); levelForMajorsDetails.setId(IdGen.uuid()); levelForMajorsDetails.setIsNewRecord(true); if(levelForMajorsDetails != null){ System.out.println("date:"+ date); levelForMajorsDetailsService.save(levelForMajorsDetails); System.out.println("保存成功!"); } else { System.out.println("levelForMajorsDetails 为null"); } List<LevelForMajorsDetails> LevelForMajorsDetailsSaved = levelForMajorsDetailsService.findByUpdate(levelForMajorsDetails); for(LevelForMajorsDetails l : LevelForMajorsDetailsSaved){ System.out.println("测试 getUpdateDate 方法中按时间获取到的记录的时间:"+l.getUpdateDate()); } LevelForMajorsDetails newLevelForMajorsDetails = new LevelForMajorsDetails(); newLevelForMajorsDetails.setUpdateDate(date); System.out.println("delect 的 date:"+ date); levelForMajorsDetailsService.deleteERecord(newLevelForMajorsDetails); System.out.println("执行了删除!"); } //测试 LevelForMajorsForDetails 中的按更新时间删除记录 @Test public void testLevelForMajorsDetailsServiceGet(){ Date date = new Date(); LevelForMajorsForDetails levelForMajorsForDetails = new LevelForMajorsForDetails(); levelForMajorsForDetails.setUpdateDate(date); if(levelForMajorsForDetails != null){ System.out.println("date:"+ date); levelForMajorsForDetailsService.save(levelForMajorsForDetails); System.out.println("保存成功!"); } else { System.out.println("levelForMajorsDetails 为null"); } List<LevelForMajorsForDetails> LevelForMajorsForDetailsSaved = levelForMajorsForDetailsService.findByUpdate(levelForMajorsForDetails); for(LevelForMajorsForDetails l : LevelForMajorsForDetailsSaved){ System.out.println("测试 getUpdateDate 方法中按时间获取到的记录的时间:"+l.getUpdateDate()); } LevelForMajorsForDetails newLevelForMajorsForDetails = new LevelForMajorsForDetails(); newLevelForMajorsForDetails.setUpdateDate(date); System.out.println("delect 的 date:"+ date); levelForMajorsForDetailsService.deleteERecord(newLevelForMajorsForDetails); System.out.println("执行了删除!"); } //测试 dZhuanyexinxibiaoService 中的 setAlreadyTransform()方法 @Test public void testDZhuanyexinxibiaoService(){ int count = dZhuanyexinxibiaoService.setAlreadyTransform(); System.out.println("成功修改了"+ count +"条记录!"); } //测试添加 beiyong20 = "" 时的查询结果是否为查询到数据库中 beiyong20=null 的记录 @Test public void testFindListByBeiyong20(){ DZhuanyexinxibiao dZhuanyexinxibiao = new DZhuanyexinxibiao(); dZhuanyexinxibiao.setBeiyong20(""); List<DZhuanyexinxibiao> dZhuanyexinxibiaoList = dZhuanyexinxibiaoService.findListByBeiyong20(dZhuanyexinxibiao); System.out.println(dZhuanyexinxibiaoList.size()); } }
  1. 好吧,还是忍受不住没有 Log4j 了,找了篇大佬博文,照着配置下。
    原博文: Junit 单元测试使用 log4j 输出日志

  Junit+spring+log4j 整合之所以麻烦,是因为 spring 与 log4j 的整合,是放在 web.xml 里的,随 tomcat 启动后,spring 才会加载 log4j,而用 junit 测试是不需要 tomcat 启动的,所以 Junit 与 log4j 的整合才比较费劲。Junit 使用 spring 时,若 spring 没加载到 log4j 就会报以下警告:

1. log4j:WARN No appenders could be found for logger(org.springframework.test.context.junit4.SpringJUnit4ClassRunner).   2. log4j:WARN Please initialize the log4j system properly.   3. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

推荐方法 
      新建 JUnit4ClassRunner 类: 

1. public class JUnit4ClassRunner extends SpringJUnit4ClassRunner {   2.     static {   3.         try {   4.             Log4jConfigurer.initLogging("classpath:com/config/log4j.properties");   5.         } catch (FileNotFoundException ex) {   6.             System.err.println("Cannot Initialize log4j");   7.         }   8.     }   9.     public JUnit4ClassRunner(Class<?> clazz) throws InitializationError {   10.         super(clazz);   11.     }   12. }

引用此类: 

1. @RunWith(JUnit4ClassRunner.class)   2. @ContextConfiguration(locations = "classpath:com/config/springConfig.xml")   3. @Transactional   4. @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)   5. public class TestHibernate {   6.     ...   7. }  

      这样,在启动 Junit 测试时,spring 就会加载 log4j 了。而且保持了灵活性。 

      PS:Junit 加载 spring 的 runner(SpringJUnit4ClassRunner)要优先于 spring 加载 log4j,因此采用普通方法,无法实现 spring 先加载 log4j 后被 Junit 加载。所以我们需要新建 JUnit4ClassRunner 类,修改 SpringJUnit4ClassRunner 加载 log4j 的策略。这样加载 log4j 就会优先于加载 spring 了。

采用前辈推荐的方法:

package com.jeeplus.core.junit; import org.junit.runners.model.InitializationError; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.Log4jConfigurer; import java.io.FileNotFoundException; /** * Created by pc on 2019/6/6. */ public class MyJUnit4ClassRunner extends SpringJUnit4ClassRunner { static { try { Log4jConfigurer.initLogging("classpath:properties/log4j.properties");//F:\pc\CEDS 本地SVN\jeeplus\src\main\resources\properties\log4j.properties properties/log4j.properties } catch (FileNotFoundException ex) { System.err.println("Cannot Initialize log4j"); } } public MyJUnit4ClassRunner(Class<?> clazz) throws InitializationError { super(clazz); } }

修改原 BaseJunit4Test 中的 @RunWith 注解中类

package com.jeeplus.core.junit; 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; /** * Created by pc on 2019/6/3. */ @RunWith(MyJUnit4ClassRunner.class)//表示整合JUnit4进行测试 @ContextConfiguration(locations={"classpath:spring/spring-context*.xml","classpath:/spring/spring-mvc*.xml"}) @WebAppConfiguration //声明以 web 形式进行测试 public class BaseJunit4Test { }

这样就可以了。最终效果:

image.png

1 操作
PeterChu 在 2019-06-06 18:22:18 更新了该帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • PeterChu
    作者
    package com.jeeplus.modules.junittest; import com.alibaba.fastjson.JSONObject; import com.jeeplus.core.junit.BaseJunit4Test; import com.jeeplus.modules.university.entity.SysAreaForUniversity; import com.jeeplus.modules.university.service.SysAreaForUniversityService; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Created by pc on 2019/6/6. */ public class TestUniversity extends BaseJunit4Test { @Autowired SysAreaForUniversityService sysAreaForUniversityService; //测试 SysAreaForUniversity 中的getByNameForCity() 方法 @Test public void testGetByNameForCity(){ SysAreaForUniversity sysAreaForUniversity = new SysAreaForUniversity(); sysAreaForUniversity.setName("北京市"); SysAreaForUniversity sa = sysAreaForUniversityService.getByNameForCity(sysAreaForUniversity); System.out.println("查询到的城市:"+ sa.getName() +","+ sa.getCode()); // String jo = JSONObject.toJSONString(sa); //此处 栈溢出 异常 // System.out.println(jo); System.out.println(sa.getId()); } }

    image.png

    还有个需要注意的地方就是:
    还没去看怎么配置下 log4j 的日志输出。
    所以,现在测试时是不能查看日志的。

  • PeterChu
    作者

    单元测试中会存在 shiro 安全验证问题:

    如下图单元测试中,调用了某个 xxxService 的 findList 方法时,会报异常,但同样的情况下有时又不会报该异常。

    image.png

    org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton. This is an invalid application configuration. at org.apache.shiro.SecurityUtils.getSecurityManager(SecurityUtils.java:123) at org.apache.shiro.subject.Subject$Builder.<init>(Subject.java:626) at org.apache.shiro.SecurityUtils.getSubject(SecurityUtils.java:56) at com.jeeplus.modules.sys.utils.UserUtils.getSession(UserUtils.java:290) at com.jeeplus.modules.sys.utils.UserUtils.getCache(UserUtils.java:313) at com.jeeplus.modules.sys.utils.UserUtils.getCache(UserUtils.java:308) at com.jeeplus.modules.sys.utils.UserUtils.getDataRuleList(UserUtils.java:190) at com.jeeplus.core.service.BaseService.dataRuleFilter(BaseService.java:37) at com.jeeplus.core.service.CrudService.findList(CrudService.java:61)

    暂时没有找到原因和解决办法,先记录下。

  • PeterChu
    作者
    1. 注意 @ContextConfiguration(locations={"classpath:spring/spring-context*.xml","classpath:/spring/spring-mvc*.xml"}) 路径问题,最好将 xml 配置文件按照此种方式放在 src/main/resources 目录内。
    2. 如果按照 IDEA+maven+SpringMVC 模式默认情况下,xml 文件位于 WEB-INF 目录下,那么此处应该如何获取呢?路径应该怎样写?
    3. 注意 classpath: 的使用。
    4. 在使用了该方式进行 junit 测试时,需要注意的是,如果某个组件对象中有通过注解注入属性,那么在测试类中不能使用 new 的方式创建对象。因为 new 方式创建出来的对象,由于没有经过容器创建自动注入,因此其中的属性对象为空,所以对于这类对象的创建,在测试类中同样应该使用注解的方式让容器来管理 bean 对象的创建。(问题:maven 项目默认的 test 文件夹未在 Spring 注解扫描范围内,为什么在测试类中同样可用使用注解?因为 @RunWith 还是因为 @WebAppConfiguration ?)
  • PeterChu
    作者

    回复上一条第 2 点:

    public class TestEmpDAO { ApplicationContext ac ; @Before public void before(){ // ac = new ClassPathXmlApplicationContext("dispatcher-servlet.xml"); // 这样是读取不到 WEB-INF 下的 xml 文件的 ac = new FileSystemXmlApplicationContext("web/WEB-INF/dispatcher-servlet.xml"); } }

    Junit 单元测试 Spring 读取 WEB-INF 下 xml 文件

PeterChu
人生是场修行,求知是种信仰 ! 西安

推荐标签 标签

  • wolai

    我来 wolai:不仅仅是未来的云端笔记!

    2 引用 • 14 回帖 • 3 关注
  • Wide

    Wide 是一款基于 Web 的 Go 语言 IDE。通过浏览器就可以进行 Go 开发,并有代码自动完成、查看表达式、编译反馈、Lint、实时结果输出等功能。

    欢迎访问我们运维的实例: https://wide.b3log.org

    30 引用 • 218 回帖 • 647 关注
  • Sym

    Sym 是一款用 Java 实现的现代化社区(论坛/BBS/社交网络/博客)系统平台。

    下一代的社区系统,为未来而构建

    524 引用 • 4601 回帖 • 710 关注
  • 叶归
    13 引用 • 59 回帖 • 22 关注
  • SQLServer

    SQL Server 是由 [微软] 开发和推广的关系数据库管理系统(DBMS),它最初是由 微软、Sybase 和 Ashton-Tate 三家公司共同开发的,并于 1988 年推出了第一个 OS/2 版本。

    21 引用 • 31 回帖 • 4 关注
  • flomo

    flomo 是新一代 「卡片笔记」 ,专注在碎片化时代,促进你的记录,帮你积累更多知识资产。

    6 引用 • 143 回帖
  • 大疆创新

    深圳市大疆创新科技有限公司(DJI-Innovations,简称 DJI),成立于 2006 年,是全球领先的无人飞行器控制系统及无人机解决方案的研发和生产商,客户遍布全球 100 多个国家。通过持续的创新,大疆致力于为无人机工业、行业用户以及专业航拍应用提供性能最强、体验最佳的革命性智能飞控产品和解决方案。

    2 引用 • 14 回帖 • 1 关注
  • Access
    1 引用 • 3 回帖
  • PWA

    PWA(Progressive Web App)是 Google 在 2015 年提出、2016 年 6 月开始推广的项目。它结合了一系列现代 Web 技术,在网页应用中实现和原生应用相近的用户体验。

    14 引用 • 69 回帖 • 184 关注
  • 程序员

    程序员是从事程序开发、程序维护的专业人员。

    591 引用 • 3528 回帖 • 1 关注
  • InfluxDB

    InfluxDB 是一个开源的没有外部依赖的时间序列数据库。适用于记录度量,事件及实时分析。

    2 引用 • 105 关注
  • WebComponents

    Web Components 是 W3C 定义的标准,它给了前端开发者扩展浏览器标签的能力,可以方便地定制可复用组件,更好的进行模块化开发,解放了前端开发者的生产力。

    1 引用 • 15 关注
  • 链滴

    链滴是一个记录生活的地方。

    记录生活,连接点滴

    183 引用 • 3885 回帖
  • Node.js

    Node.js 是一个基于 Chrome JavaScript 运行时建立的平台, 用于方便地搭建响应速度快、易于扩展的网络应用。Node.js 使用事件驱动, 非阻塞 I/O 模型而得以轻量和高效。

    139 引用 • 269 回帖 • 2 关注
  • Telegram

    Telegram 是一个非盈利性、基于云端的即时消息服务。它提供了支持各大操作系统平台的开源的客户端,也提供了很多强大的 APIs 给开发者创建自己的客户端和机器人。

    5 引用 • 35 回帖
  • Kubernetes

    Kubernetes 是 Google 开源的一个容器编排引擎,它支持自动化部署、大规模可伸缩、应用容器化管理。

    118 引用 • 54 回帖 • 5 关注
  • 设计模式

    设计模式(Design pattern)代表了最佳的实践,通常被有经验的面向对象的软件开发人员所采用。设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案。这些解决方案是众多软件开发人员经过相当长的一段时间的试验和错误总结出来的。

    201 引用 • 120 回帖 • 3 关注
  • Mobi.css

    Mobi.css is a lightweight, flexible CSS framework that focus on mobile.

    1 引用 • 6 回帖 • 766 关注
  • 旅游

    希望你我能在旅途中找到人生的下一站。

    100 引用 • 905 回帖
  • Linux

    Linux 是一套免费使用和自由传播的类 Unix 操作系统,是一个基于 POSIX 和 Unix 的多用户、多任务、支持多线程和多 CPU 的操作系统。它能运行主要的 Unix 工具软件、应用程序和网络协议,并支持 32 位和 64 位硬件。Linux 继承了 Unix 以网络为核心的设计思想,是一个性能稳定的多用户网络操作系统。

    955 引用 • 944 回帖 • 1 关注
  • Solo

    Solo 是一款小而美的开源博客系统,专为程序员设计。Solo 有着非常活跃的社区,可将文章作为帖子推送到社区,来自社区的回帖将作为博客评论进行联动(具体细节请浏览 B3log 构思 - 分布式社区网络)。

    这是一种全新的网络社区体验,让热爱记录和分享的你不再感到孤单!

    1444 引用 • 10083 回帖 • 507 关注
  • 招聘

    哪里都缺人,哪里都不缺人。

    188 引用 • 1057 回帖
  • BAE

    百度应用引擎(Baidu App Engine)提供了 PHP、Java、Python 的执行环境,以及云存储、消息服务、云数据库等全面的云服务。它可以让开发者实现自动地部署和管理应用,并且提供动态扩容和负载均衡的运行环境,让开发者不用考虑高成本的运维工作,只需专注于业务逻辑,大大降低了开发者学习和迁移的成本。

    19 引用 • 75 回帖 • 681 关注
  • 996
    13 引用 • 200 回帖 • 1 关注
  • Rust

    Rust 是一门赋予每个人构建可靠且高效软件能力的语言。Rust 由 Mozilla 开发,最早发布于 2014 年 9 月。

    59 引用 • 22 回帖 • 6 关注
  • 自由行
    1 关注
  • 机器学习

    机器学习(Machine Learning)是一门多领域交叉学科,涉及概率论、统计学、逼近论、凸分析、算法复杂度理论等多门学科。专门研究计算机怎样模拟或实现人类的学习行为,以获取新的知识或技能,重新组织已有的知识结构使之不断改善自身的性能。

    77 引用 • 37 回帖