一、教程

转载:https://blog.csdn.net/sdyy321/article/details/38757135/

官网: http://mockito.org

源码分析:https://www.cnblogs.com/dengshihuang/p/7903550.html

属性默认值:https://yanbin.blog/mockito-mocked-default-fields-method-returns/#more-8359

API文档:http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html

项目源码:https://github.com/mockito/mockito
使用案例:https://blog.csdn.net/Christopher36/article/details/81036683

首先添加maven依赖

 <dependency>
          <groupId>org.mockito</groupId>
          <artifactId>mockito-all</artifactId>
          <version>1.9.5</version>
          <scope>test</scope>
      </dependency>

当然mockito需要junit配合使用

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>

然后为了使代码更简洁,最好在测试类中导入静态资源

import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

下面我们开始使用mockito来做测试

package com.spring.sxf.mockito;

import org.junit.Test;
import org.mockito.ArgumentMatcher;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.exceptions.verification.NoInteractionsWanted; import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List; import static org.mockito.Mockito.*;
import static org.junit.Assert.*; /**
* @author <a href="mailto:shangxiaofei@meituan.com">尚晓飞</a>
* @date 7:52 PM 2019/4/26
*/
public class MockitoTest { //验证要mock的对象,是否发生过某些行为
@Test
public void testArrayList() {
//生成mock对象
ArrayList<String> mockList = mock(ArrayList.class);
//使用mock的对象
mockList.add("SXF");
mockList.add("456"); //验证行为add("SXF"),add("123")是否发生过
verify(mockList).add("SXF");
verify(mockList).add("456");
} //模拟我们所期望的结果
@Test
public void testArrayList1() {
//生成mock对象
ArrayList<String> mockList = mock(ArrayList.class);
//
when(mockList.size()).thenReturn(2);
int size = mockList.size();
assertEquals(2, size); } //模拟我们期望的结果
@Test(expected = NullPointerException.class)
public void when_thenThrow() throws IOException {
OutputStream outputStream = mock(OutputStream.class);
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
//预设当流关闭时抛出异常
doThrow(new IOException()).when(outputStream).close();
outputStream.close();
} //参数匹配
@Test
public void with_arguments() {
Comparable comparable = mock(Comparable.class);
//预设根据不同的参数返回不同的结果
when(comparable.compareTo("Test")).thenReturn(1);
when(comparable.compareTo("Omg")).thenReturn(2);
assertEquals(1, comparable.compareTo("Test"));
assertEquals(2, comparable.compareTo("Omg"));
//对于没有预设的情况会返回默认值
assertEquals(0, comparable.compareTo("Not stub"));
} //除了匹配制定参数外,还可以匹配自己想要的任意参数
@Test
public void with_unspecified_arguments() {
List list = mock(List.class);
//匹配任意参数
when(list.get(anyInt())).thenReturn(1);
when(list.contains(argThat(new IsValid()))).thenReturn(true);
assertEquals(1, list.get(1));
assertEquals(1, list.get(999));
assertTrue(list.contains(1));
assertTrue(!list.contains(3));
} private class IsValid extends ArgumentMatcher<List> {
@Override
public boolean matches(Object o) {
return (Integer) o == 1 || (Integer) o == 2;
}
} //需要注意的是如果你使用了参数匹配,那么所有的参数都必须通过matchers来匹配
@Test
public void all_arguments_provided_by_matchers() {
Comparator comparator = mock(Comparator.class);
comparator.compare("nihao", "hello");
//如果你使用了参数匹配,那么所有的参数都必须通过matchers来匹配
verify(comparator).compare(anyString(), eq("hello"));
//下面的为无效的参数匹配使用
//verify(comparator).compare(anyString(),"hello");
} //验证确切的调用次数
@Test
public void verifying_number_of_invocations() {
List list = mock(List.class);
list.add(1);
list.add(2);
list.add(2);
list.add(3);
list.add(3);
list.add(3);
//验证是否被调用一次,等效于下面的times(1)
verify(list).add(1);
verify(list, times(1)).add(1);
//验证是否被调用2次
verify(list, times(2)).add(2);
//验证是否被调用3次
verify(list, times(3)).add(3);
//验证是否从未被调用过
verify(list, never()).add(4);
//验证至少调用一次
verify(list, atLeastOnce()).add(1);
//验证至少调用2次
verify(list, atLeast(2)).add(2);
//验证至多调用3次
verify(list, atMost(3)).add(3); } //模拟方法体抛出异常
@Test(expected = RuntimeException.class)
public void doThrow_when() {
List list = mock(List.class);
doThrow(new Exception()).when(list).add(1);
list.add(1);
} //验证执行顺序
@Test
public void verification_in_order() {
List list = mock(List.class);
List list2 = mock(List.class);
list.add(1);
list2.add("hello");
list.add(2);
list2.add("world");
//将需要排序的mock对象放入InOrder
InOrder inOrder = inOrder(list, list2);
//下面的代码不能颠倒顺序,验证执行顺序
inOrder.verify(list).add(1);
inOrder.verify(list2).add("hello");
inOrder.verify(list).add(2);
inOrder.verify(list2).add("world");
} //确保模拟对象上无互动发生
@Test
public void verify_interaction(){
List list = mock(List.class);
List list2 = mock(List.class);
List list3 = mock(List.class);
list.add(1);
verify(list).add(1);
verify(list,never()).add(2);
//验证零互动行为
verifyZeroInteractions(list2,list3);
} //找出冗余的互动(即未被验证到的)
@Test(expected = NoInteractionsWanted.class)
public void find_redundant_interaction(){
List list = mock(List.class);
list.add(1);
list.add(2);
verify(list,times(2)).add(anyInt());
//检查是否有未被验证的互动行为,因为add(1)和add(2)都会被上面的anyInt()验证到,所以下面的代码会通过
verifyNoMoreInteractions(list); List list2 = mock(List.class);
list2.add(1);
list2.add(2);
verify(list2).add(1);
//检查是否有未被验证的互动行为,因为add(2)没有被验证,所以下面的代码会失败抛出异常
verifyNoMoreInteractions(list2);
} //9、使用注解来快速模拟
//在上面的测试中我们在每个测试方法里都mock了一个List对象,为了避免重复的mock,是测试类更具有可读性,我们可以使用下面的注解方式来快速模拟对象:
@Mock
private List mockList;
//构造方法
public MockitoTest(){
MockitoAnnotations.initMocks(this);
} @Test
public void shorthand(){
mockList.add(1);
verify(mockList).add(1);
} }

二、spring项目+单元测试使用mockito

一、单元测试类

@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/applicationContext.xml"})
public class RouteServiceTest { //要被mock的接口
@Mock
private IChannelQueueCountService iChannelQueueCountService; //使用了要被mock对象的类,需要注入mock对象
@InjectMocks
@Autowired
private ChannelChooseService channelChooseService; //发起调用的接口
@Autowired
private TRouteService.Iface tRouteService; //mock对象注入
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
} @Test
public void test01() throws TException { when(iChannelQueueCountService.getChannelQueueCounts(anyList(), anyLong(), anyBoolean())).thenAnswer(new Answer<Map<Integer, Integer>>() { @Override
public Map<Integer, Integer> answer(InvocationOnMock invocation) throws Throwable {
HashMap<Integer, Integer> map = new HashMap<>();
Object[] args = invocation.getArguments();
List<Integer> ids = (List<Integer>) args[0];
for (Integer id : ids) {
map.put(id, 1);
}
return map;
}
}); TChooseChannelReq tChooseChannelReq = new TChooseChannelReq(56789, 219, 999, 6000, "shangxiaofei", "6212260200052453285", TPPType.PRIVATE, 10, 34, 99999);
TChooseChannelRes res = tRouteService.chooseChannel(tChooseChannelReq);
System.out.println("接口调用返回:" + res.getLogicalChannelId()); }
}

【项目经验】Mockito教程的更多相关文章

  1. Mockito教程

    Mockito教程 2017-01-20 目录 1 Mockito 介绍   1.1 Mockito是什么?  1.2 为什么需要Mock  1.3 Stub和Mock异同  1.4 Mockito资 ...

  2. 最近面试java后端开发的感受:如果就以平时项目经验来面试,通过估计很难——再论面试前的准备

    在上周,我密集面试了若干位Java后端的候选人,工作经验在3到5年间.我的标准其实不复杂:第一能干活,第二Java基础要好,第三最好熟悉些分布式框架,我相信其它公司招初级开发时,应该也照着这个标准来面 ...

  3. 【建议收藏】缺少 Vue3 和 Spring Boot 的实战项目经验?我这儿有啊!

    缺少 Vue3 和 Spring Boot 的实战项目经验?缺少学习项目和练手项目?我这儿有啊! 从 2019 年到 2021 年,空闲时间里陆陆续续做了一些开源项目,推荐给大家啊!记得点赞和收藏噢! ...

  4. 《项目经验》--通过js获取前台数据向一般处理程序传递Json数据,并解析Json数据,将前台传来的Json数据写入数据库表中

      先看一下我要实现的功能界面:   这个界面的功能在图中已有展现,课程分配(教师教授哪门课程)在之前的页面中已做好.这个页面主要实现的是授课,即给老师教授的课程分配学生.此页面实现功能的步骤已在页面 ...

  5. Java项目经验——程序员成长的关键(转载)

    Java就是用来做项目的!Java的主要应用领域就是企业级的项目开发!要想从事企业级的项目开发,你必须掌握如下要点:1.掌握项目开发的基本步骤2.具备极强的面向对象的分析与设计技巧3.掌握用例驱动.以 ...

  6. Java项目经验

    Java项目经验 转自CSDN. Java就是用来做项目的!Java的主要应用领域就是企业级的项目开发!要想从事企业级的项目开发,你必须掌握如下要点:1.掌握项目开发的基本步骤2.具备极强的面向对象的 ...

  7. OSG项目经验2<在场景中添加文字面版>

    添加文字版需要用到osg的三个名字空间:                         osgText::Text,这个类用来添加文字和设置文字的一些属性:                     ...

  8. java程序员面试交流项目经验

    粘贴自:https://blog.csdn.net/wangyuxuan_java/article/details/8778211 1:请你介绍一下你自己 这是面试官常问的问题.一般人回答这个问题过于 ...

  9. 新巴巴运动网上商城 项目 快速搭建 教程 The new babar sports online mall project quickly builds a tutorial

    新巴巴运动网上商城 项目 快速搭建 教程 The new babar sports online mall project quickly builds a tutorial 作者:韩梦飞沙 Auth ...

  10. 项目经验分享[转自min.jiang]

        最近三个月,我非常荣幸的做为TeamLeader带领几个小组成员做了一个国外项目,这里想为大家分享一些小经验,尽管我佣有六年多的项目经验,但我一直的方向是架构师.大家知道架构师一般情况是偏向技 ...

随机推荐

  1. Write CSV file for a dataset

    import numpy as np import cv2 as cv2 import os import csv dataste_path = 'datasets/pascal-parts/pasc ...

  2. 本地存储localStorage sessionStorage 以及 session 和cookie的对比和使用

    cookie和session都是用来跟踪浏览器用户身份的会话方式. 1.验证当前服务中继续请求数据时,哪些缓存数据会随着发往服务器? 只有cookie中设置的缓存数据会发送到服务器端 2. 强调几点: ...

  3. 初识Hibernate框架,进行简单的增删改查操作

    Hibernate的优势 优秀的Java 持久化层解决方案  (DAO) 主流的对象—关系映射工具产品 简化了JDBC 繁琐的编码 将数据库的连接信息都存放在配置文件 自己的ORM框架 一定要手动实现 ...

  4. python模块和包(模块、包、发布模块)

    模块和包 目标 模块 包 发布模块 01. 模块 1.1 模块的概念 模块是 Python 程序架构的一个核心概念 每一个以扩展名 py 结尾的 Python 源代码文件都是一个 模块 模块名 同样也 ...

  5. Promise学习使用

    Promise是承诺的意思,“承诺可以获取异步操作的消息”,是一种异步执行的方案,Promise有各种开源实现,在ES6中被统一规范,由浏览器直接支持. Promise 对象有三种状态:pending ...

  6. Blinn-Phong模型

    最近在看基础光照模型,比较感兴趣的是高光反射模型,有下列两种: 1.Phong模型 R = 2*N(dot(N, L)) - L specular = lightColor * SpecularCol ...

  7. 三星Galaxy S8 刷机经验记录

    这段时间用上了三星S8,由于原生系统太耗电,所以萌生了root的想法.写这篇博客记录下这段时间的各种尝试. Root过程说明: 友情提示,道路千万条,安全第一条.开始捣鼓手机之前请一定准备好官方的救砖 ...

  8. 第四次Scrum编码冲刺

    第四次Scrum编码冲刺!!!! 一.总体任务: 本次冲刺是完成对图书馆管理系统的最后三个功能的实现------管理员对用户授权.用户注销和用户查询 二.个人任务及完成情况:    本人本次的任务是实 ...

  9. 使用lua实现99乘法口诀表,就这么简洁

    for i=1,9 do for j=1,i do io.write(j,"*",i,"=",i*j," ") end print() en ...

  10. 洛谷 P1047 校门外的树

    #include<iostream> #include<vector> #include<algorithm> using namespace std; ]; in ...