Mockito在JUnit测试中的使用
Mockito是一种用于替代在测试中难以实现的成员,从而让testcase能顺利覆盖到目标代码的手段。下面例子将展示Mockito的使用。
完整代码下载:https://files.cnblogs.com/files/xiandedanteng/mockitoTest20200311.zip
首先有这么一个需要测试的类:
package mockito; public class EmpService {
private EmpDao dao; public EmpService() {
dao=new EmpDao();
} public boolean isWeakPswd(long empId) {
// roadlock which hinder running bacause of no environment
Emp emp=dao.getById(empId); // Real code need to be tested,but unreachable because emp is null
if(emp.getPswd().equals("111111")) {
return true;
}else if(emp.getPswd().equals("123456")) {
return true;
}else if(emp.getName().equals(emp.getPswd())) {
return true;
}else {
return false;
}
}
}
其中isWeakPswd是需要测试的方法,但问题是dao不能在测试环境中就绪,因此跑不到下面的if语句。
package mockito; public class EmpDao {
public Emp getById(long id) {
// Access auth/redis/db to get a real emp,but it is difficult to set up environment in test,so return null
return null;
}
}
EmpDao的getById方法不能就绪的原因是需要搭建完整的认证/redis/db环境,总之搞不成就是了。大家在测试某些类也会发生内部的mapper,dao不能就绪的情况,这和本例情况类似。
然后下面的测试方法就走不下去了,因为一跑isWeakPswd方法就会抛出空指针异常;
@Test
public void normalTestWeakPswd() {
EmpService service=new EmpService(); // NullPointerException will be thrown out and case will fail
boolean actual=service.isWeakPswd(10001); Assert.assertSame(true, actual);
}
然后怎么办呢?任凭Coverrage在低位徘徊?当然不是,这个时候就该请Mock出场了。
Mock本身就是个空壳,作用是替代无法就绪的对象,达到测试其后代码的目的。下面就制作了mockDao用来替代EmpService里的empDao
@Test
public void testWeakPswd_ByMock_01() throws Exception {
EmpDao mockDao = Mockito.mock(EmpDao.class); // 创建
Emp emp=new Emp(10001,"Andy","111111"); // 返回值
Mockito.when(mockDao.getById(10001)).thenReturn(emp);// 设置调用getById时返回固定值 // Use reflection replace dao with mockDao,利用反射用mock对象取代原有的empDao
EmpService service=new EmpService();
Field daoField = service.getClass().getDeclaredField("dao");
daoField.setAccessible(true);
daoField.set(service, mockDao); Assert.assertEquals(true, service.isWeakPswd(10001));// 这样,isWeakPswd方法就不会抛出空指针异常了
}
这样,Mock对象就当好了替补队员的角色,使得isWeakPswd的代码可以达到了。
Mockito的使用就这样简单,无非是创建,设定要模拟的函数的返回值(或异常),然后用反射方法进行顶替三部曲,下面是测试类的全部代码:
package mockitoTest; import java.lang.reflect.Field; import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito; import mockito.Emp;
import mockito.EmpDao;
import mockito.EmpService; public class EmpServiceTest {
@Rule
public ExpectedException exception = ExpectedException.none(); // No Exception thrown Allowed private EmpDao memberMockDao; @Before
public void init() throws Exception {
memberMockDao = Mockito.mock(EmpDao.class);
Emp emp=new Emp(10002,"Bill","123456");
Mockito.when(memberMockDao.getById(10002)).thenReturn(emp);
} @Test
public void normalTestWeakPswd() {
EmpService service=new EmpService(); // NullPointerException will be thrown out and case will fail
boolean actual=service.isWeakPswd(10001); Assert.assertSame(true, actual);
} @Test
public void testWeakPswd_ByMock_01() throws Exception {
EmpDao mockDao = Mockito.mock(EmpDao.class);
Emp emp=new Emp(10001,"Andy","111111");
Mockito.when(mockDao.getById(10001)).thenReturn(emp); // Use reflection replace dao with mockDao
EmpService service=new EmpService();
Field daoField = service.getClass().getDeclaredField("dao");
daoField.setAccessible(true);
daoField.set(service, mockDao); Assert.assertEquals(true, service.isWeakPswd(10001));
} @Test
public void testWeakPswd_ByMock_02() throws Exception { // Use reflection replace dao with mockDao
EmpService service=new EmpService();
Field daoField = service.getClass().getDeclaredField("dao");
daoField.setAccessible(true);
daoField.set(service, memberMockDao); Assert.assertEquals(true, service.isWeakPswd(10002));
} @Test
public void testWeakPswd_ByMock_03() throws Exception {
EmpDao mockDao = Mockito.mock(EmpDao.class);
Emp emp=new Emp(10003,"Cindy","Cindy");
Mockito.when(mockDao.getById(10003)).thenReturn(emp); // Use reflection replace dao with mockDao
EmpService service=new EmpService();
Field daoField = service.getClass().getDeclaredField("dao");
daoField.setAccessible(true);
daoField.set(service, mockDao); Assert.assertEquals(true, service.isWeakPswd(10003));
}
}
要测试的EmpService类:
package mockito; public class EmpService {
private EmpDao dao; public EmpService() {
dao=new EmpDao();
} public boolean isWeakPswd(long empId) {
// roadlock which hinder running bacause of no environment
Emp emp=dao.getById(empId); // Real code need to be test,but unreachable because emp is null
if(emp.getPswd().equals("111111")) {
return true;
}else if(emp.getPswd().equals("123456")) {
return true;
}else if(emp.getName().equals(emp.getPswd())) {
return true;
}else {
return false;
}
}
}
因伤不能上阵的EmpDao类:
package mockito; public class EmpDao {
public Emp getById(long id) {
// Access auth/redis/db to get a real emp,but it is difficult to set up environment in test,so return null
return null;
}
}
实体类Emp:
package mockito; public class Emp {
private long id;
private String name;
private String pswd; public Emp() { } public Emp(long id,String name,String pswd) {
this.id=id;
this.name=name;
this.pswd=pswd;
} public long getId() {
return id;
} public void setId(long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getPswd() {
return pswd;
} public void setPswd(String pswd) {
this.pswd = pswd;
}
}
要使用Mockito,可以在pom.xml里进行如以下红字部分设置:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>logbackCfg</artifactId>
<version>0.0.1-SNAPSHOT</version> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.11</version>
</dependency> <dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.11</version>
</dependency> <dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.1.0</version>
<scope>test</scope>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
--2020年3月11日--
参考资料:http://www.voidcn.com/article/p-vekqzrow-btm.html
Mock与反射关系不小,这里是反射资料:https://blog.csdn.net/a745233700/article/details/82893076
反射资料2:https://www.sczyh30.com/posts/Java/java-reflection-1/
Mockito在JUnit测试中的使用的更多相关文章
- Junit测试中的setup和teardown 和 @before 和 @After 方法
这几天做Junit测试接触到了setup和teardown两个方法,简单的可以这样理解它们,setup主要实现测试前的初始化工作,而teardown则主要实现测试完成后的垃圾回收等工作. 需要注意的是 ...
- Junit测试中找不到junit.framework.testcase
在使用Junit进行测试时,出现如下问题: 找不到junit.framework.testcase 解决方法: 选中项目->属性->Java构建路径->库->添加外部jar 在 ...
- java Junit 测试中异常处理
错误提示: junit.framework.AssertionFailedError: No tests found in错误解决办法 用junit Test运行后,出现如下的错误:junit.fra ...
- Eclipse中Junit测试中@Before不执行
场景 在使用Junit进行单元测试时,一部分获取JPA的entityManager的代码将其放在了 @Before标注的方法中,这样每次执行@TEST标注的方法时会首先执行@Before标注的方法. ...
- Junit mockito解耦合测试
Mock测试是单元测试的重要方法之一. 1.相关网址 官网:http://mockito.org/ 项目源码:https://github.com/mockito/mockito api:http:/ ...
- Javaspring+mybit+maven中实现Junit测试类
在一个Javaspring+mybit+maven框架中,增加Junit测试类. 在测试类中遇到的一些问题,利用spring 框架时,里面已经有保密security+JWT设定的场合,在你的secur ...
- 在Eclipse中生成接口的JUnit测试类
在Spring相关应用中,我们经常使用“接口” + “实现类” 的形式,为了方便,使用Eclipse自动生成Junit测试类. 1. 类名-new-Other-java-Junit-Junit Tes ...
- JUnit测试工具在项目中的用法
0:33 2013/6/26 三大框架整合时为什么要对项目进行junit测试: |__目的是测试配置文件对不对,能跑通就可以进行开发了 具体测试步骤: |__1.对hibernate进行测试 配置hi ...
- Junit 4 测试中使用定时任务操作
难度:测试中执行线程操作 package com.hfepc.job.dataCollection.test; import java.util.Date; import java.util.List ...
随机推荐
- Netty之旅:你想要的NIO知识点,这里都有!
高清思维导图原件(xmind/pdf/jpg)可以关注公众号:一枝花算不算浪漫 回复nio即可.(文末有二维码) 前言 抱歉好久没更原创文章了,看了下上篇更新时间,已经拖更一个多月了. 这段时间也一直 ...
- AAPT: error: resource android:attr/dialogCornerRadius not found. Android resource linking failed
打开android\app\build.gradle 修改 compileSdkVersion 和 targetSdkVersion
- C#LeetCode刷题之#695-岛屿的最大面积( Max Area of Island)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3736 访问. 给定一个包含了一些 0 和 1的非空二维数组 gr ...
- js中几种常用的数组处理方法的总结
一.filter()用法 功能:用于筛选数组中满足条件的元素,返回一个筛选后的新数组. <script> $(function(){ var arr = [1,-2,3,4,-5]; va ...
- 初识ABP vNext(2):ABP启动模板
目录 前言 开始 AbpHelper 模块安装 最后 前言 上一篇介绍了ABP的一些基础知识,本篇继续介绍ABP的启动模板.使用ABP CLI命令就可以得到这个启动模板,其中包含了一些基础功能模块,你 ...
- 如何去除List集合中的重复元素?
一.问题由来 在实际开发的时候,我们经常会碰到这么一个问题:一个集合容器里面有很多重复的对象,里面的对象没有主键,或者说忽略主键,根据业务的需求,我们需要根据条件筛选出没有重复的对象. 二.去重操作 ...
- 面试官最爱的 volatile 关键字,这些问题你都搞懂了没?
前言 volatile相关的知识点,在面试过程中,属于基础问题,是必须要掌握的知识点,如果回答不上来会严重扣分的哦. volatile关键字基本介绍 volatile可以看成是synchronized ...
- IE9知识点汇总
1.首先ie9不支持flex布局,只能使用float,要想支持ie低版本,两者要同时使用. 2.input框不支持placeholder属性,只能自己加span标签模拟出来,调整样式. 3.单个css ...
- Linux C++实现一服务器与多客户端之间的通信
通过网络查找资料得到的都是一些零碎不成体系的知识点,无法融会贯通.而且需要筛选有用的信息,这需要花费大量的时间.所以把写代码过程中用到的相关知识的博客链接附在用到的位置,方便回顾. 1.程序流程 服务 ...
- Java反射概念与基础
反射机制是Java动态性之一,而说到动态性首先得了解动态语言.那么何为动态语言? 一.动态语言 动态语言,是指程序在运行时可以改变其结构:新的函数可以引进,已有的函数可以被删除等结构上的变化.比如常见 ...