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 ...
随机推荐
- Django中间件之实现Admin后台IP白名单
Django自带的Admin管理后台很方便,但是实际生产环境真的会有挺多安全问题的,在admin的安全防护这方面,我之前就研究实现了给admin加上登录验证码和限流功能,可以参考这篇文章: 不过就在内 ...
- 狄利克雷卷积 & 莫比乌斯反演
积性函数与完全积性函数 积性函数 若一个数论函数\(f\)满足当\(gcd(n,m)=1\)时,\(f(nm)=f(n)f(m)\) 则称\(f\)为积性函数 一些常见的积性函数 完全积性函数 若一个 ...
- (数据科学学习手札92)利用query()与eval()优化pandas代码
本文示例代码已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 1 简介 利用pandas进行数据分析的过程,不仅仅是计算 ...
- 每日一道 LeetCode (14):数组加一
每天 3 分钟,走上算法的逆袭之路. 前文合集 每日一道 LeetCode 前文合集 代码仓库 GitHub: https://github.com/meteor1993/LeetCode Gitee ...
- GUAVA-cache实现
GUAVA Cache Guava Cache与ConcurrentMap很相似基于分段锁及线程安全,但也不完全一样.最基本的区别是ConcurrentMap会一直保存所有添加的元素,直到显式地移除 ...
- circos pipeline
# /usr/bin/env python# coding=utf-8#################################### Author : yunkeli# Version : ...
- cinder 卷迁移进度的代码分析
一.cinder-api服务的入口函数 D:\code-program\cinder-ocata_cinder\cinder\api\contrib\admin_actions.py from cin ...
- 淘宝小广告的鼠标移上实现html, JavaScript代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 分块练习C. interval
分块练习C. interval 题目描述 \(N\)个数\(a_i\),\(m\)个操作 \(1\). 从第一个数开始,每隔\(k_i\)个的位置上的数增加\(x_i\) \(2\). 查询\(l\) ...
- HM16.0之帧间Merge模式——xCheckRDCostMerge2Nx2N
参考:https://blog.csdn.net/nb_vol_1/article/details/51163625 1.源代码: /** check RD costs for a CU block ...