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

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

[初学者级别]

在刚开始接触 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
    作者
    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
    作者

    单元测试中会存在 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
    作者

    回复上一条第 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
人生是场修行,求知是种信仰 ! 西安

推荐标签 标签

  • SVN

    SVN 是 Subversion 的简称,是一个开放源代码的版本控制系统,相较于 RCS、CVS,它采用了分支管理系统,它的设计目标就是取代 CVS。

    29 引用 • 98 回帖 • 689 关注
  • abitmean

    有点意思就行了

    29 关注
  • IDEA

    IDEA 全称 IntelliJ IDEA,是一款 Java 语言开发的集成环境,在业界被公认为最好的 Java 开发工具之一。IDEA 是 JetBrains 公司的产品,这家公司总部位于捷克共和国的首都布拉格,开发人员以严谨著称的东欧程序员为主。

    180 引用 • 400 回帖
  • B3log

    B3log 是一个开源组织,名字来源于“Bulletin Board Blog”缩写,目标是将独立博客与论坛结合,形成一种新的网络社区体验,详细请看 B3log 构思。目前 B3log 已经开源了多款产品:SymSoloVditor思源笔记

    1083 引用 • 3461 回帖 • 261 关注
  • RYMCU

    RYMCU 致力于打造一个即严谨又活泼、专业又不失有趣,为数百万人服务的开源嵌入式知识学习交流平台。

    4 引用 • 6 回帖 • 51 关注
  • GitBook

    GitBook 使您的团队可以轻松编写和维护高质量的文档。 分享知识,提高团队的工作效率,让用户满意。

    3 引用 • 8 回帖
  • Kafka

    Kafka 是一种高吞吐量的分布式发布订阅消息系统,它可以处理消费者规模的网站中的所有动作流数据。 这种动作(网页浏览,搜索和其他用户的行动)是现代系统中许多功能的基础。 这些数据通常是由于吞吐量的要求而通过处理日志和日志聚合来解决。

    35 引用 • 35 回帖 • 4 关注
  • Shell

    Shell 脚本与 Windows/Dos 下的批处理相似,也就是用各类命令预先放入到一个文件中,方便一次性执行的一个程序文件,主要是方便管理员进行设置或者管理用的。但是它比 Windows 下的批处理更强大,比用其他编程程序编辑的程序效率更高,因为它使用了 Linux/Unix 下的命令。

    122 引用 • 73 回帖 • 1 关注
  • Ubuntu

    Ubuntu(友帮拓、优般图、乌班图)是一个以桌面应用为主的 Linux 操作系统,其名称来自非洲南部祖鲁语或豪萨语的“ubuntu”一词,意思是“人性”、“我的存在是因为大家的存在”,是非洲传统的一种价值观,类似华人社会的“仁爱”思想。Ubuntu 的目标在于为一般用户提供一个最新的、同时又相当稳定的主要由自由软件构建而成的操作系统。

    123 引用 • 168 回帖
  • CentOS

    CentOS(Community Enterprise Operating System)是 Linux 发行版之一,它是来自于 Red Hat Enterprise Linux 依照开放源代码规定释出的源代码所编译而成。由于出自同样的源代码,因此有些要求高度稳定的服务器以 CentOS 替代商业版的 Red Hat Enterprise Linux 使用。两者的不同在于 CentOS 并不包含封闭源代码软件。

    238 引用 • 224 回帖
  • LeetCode

    LeetCode(力扣)是一个全球极客挚爱的高质量技术成长平台,想要学习和提升专业能力从这里开始,充足技术干货等你来啃,轻松拿下 Dream Offer!

    209 引用 • 72 回帖
  • Quicker

    Quicker 您的指尖工具箱!操作更少,收获更多!

    25 引用 • 83 回帖
  • 开源中国

    开源中国是目前中国最大的开源技术社区。传播开源的理念,推广开源项目,为 IT 开发者提供了一个发现、使用、并交流开源技术的平台。目前开源中国社区已收录超过两万款开源软件。

    7 引用 • 86 回帖
  • jsDelivr

    jsDelivr 是一个开源的 CDN 服务,可为 npm 包、GitHub 仓库提供免费、快速并且可靠的全球 CDN 加速服务。

    5 引用 • 31 回帖 • 53 关注
  • Webswing

    Webswing 是一个能将任何 Swing 应用通过纯 HTML5 运行在浏览器中的 Web 服务器,详细介绍请看 将 Java Swing 应用变成 Web 应用

    1 引用 • 15 回帖 • 632 关注
  • CloudFoundry

    Cloud Foundry 是 VMware 推出的业界第一个开源 PaaS 云平台,它支持多种框架、语言、运行时环境、云平台及应用服务,使开发人员能够在几秒钟内进行应用程序的部署和扩展,无需担心任何基础架构的问题。

    5 引用 • 18 回帖 • 155 关注
  • SSL

    SSL(Secure Sockets Layer 安全套接层),及其继任者传输层安全(Transport Layer Security,TLS)是为网络通信提供安全及数据完整性的一种安全协议。TLS 与 SSL 在传输层对网络连接进行加密。

    69 引用 • 190 回帖 • 483 关注
  • SQLite

    SQLite 是一个进程内的库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。SQLite 是全世界使用最为广泛的数据库引擎。

    4 引用 • 7 回帖 • 1 关注
  • WebComponents

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

    1 引用 • 15 关注
  • InfluxDB

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

    2 引用 • 60 关注
  • Google

    Google(Google Inc.,NASDAQ:GOOG)是一家美国上市公司(公有股份公司),于 1998 年 9 月 7 日以私有股份公司的形式创立,设计并管理一个互联网搜索引擎。Google 公司的总部称作“Googleplex”,它位于加利福尼亚山景城。Google 目前被公认为是全球规模最大的搜索引擎,它提供了简单易用的免费服务。不作恶(Don't be evil)是谷歌公司的一项非正式的公司口号。

    49 引用 • 192 回帖 • 1 关注
  • HBase

    HBase 是一个分布式的、面向列的开源数据库,该技术来源于 Fay Chang 所撰写的 Google 论文 “Bigtable:一个结构化数据的分布式存储系统”。就像 Bigtable 利用了 Google 文件系统所提供的分布式数据存储一样,HBase 在 Hadoop 之上提供了类似于 Bigtable 的能力。

    17 引用 • 6 回帖 • 58 关注
  • VirtualBox

    VirtualBox 是一款开源虚拟机软件,最早由德国 Innotek 公司开发,由 Sun Microsystems 公司出品的软件,使用 Qt 编写,在 Sun 被 Oracle 收购后正式更名成 Oracle VM VirtualBox。

    10 引用 • 2 回帖 • 10 关注
  • 智能合约

    智能合约(Smart contract)是一种旨在以信息化方式传播、验证或执行合同的计算机协议。智能合约允许在没有第三方的情况下进行可信交易,这些交易可追踪且不可逆转。智能合约概念于 1994 年由 Nick Szabo 首次提出。

    1 引用 • 11 回帖 • 10 关注
  • frp

    frp 是一个可用于内网穿透的高性能的反向代理应用,支持 TCP、UDP、 HTTP 和 HTTPS 协议。

    16 引用 • 7 回帖 • 1 关注
  • App

    App(应用程序,Application 的缩写)一般指手机软件。

    90 引用 • 383 回帖 • 1 关注
  • Oracle

    Oracle(甲骨文)公司,全称甲骨文股份有限公司(甲骨文软件系统有限公司),是全球最大的企业级软件公司,总部位于美国加利福尼亚州的红木滩。1989 年正式进入中国市场。2013 年,甲骨文已超越 IBM,成为继 Microsoft 后全球第二大软件公司。

    103 引用 • 126 回帖 • 442 关注