mockito使用心得
前提:pom引用
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.5.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
</dependency> 背景:
方便后台开发自测接口,去除对象之间的复杂依赖,关注代码逻辑的正确性。
原理:
Mockito就是用Java提供的Dynamic Proxy API来实现的。 以下是简单的小demo:
package com.mock; import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener; /**
* 所以测试类的基类
*
* @author tom_plus
* @date 2017-01-02-17:20
*/
@ContextConfiguration(locations = {"classpath:applicationContext-test.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners(listeners = {DependencyInjectionTestExecutionListener.class,
TransactionalTestExecutionListener.class})
public class AbstractServiceIT {
}
package com.mock.demo; import com.AopTargetUtils;
import com.mock.AbstractServiceIT;
import com.springapp.bean.Teacher;
import com.springapp.service.TeacherService;
import com.springapp.service.TestService;
import com.springapp.utils.SessionContext;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.transaction.annotation.Transactional;
import org.testng.Assert; import java.util.List; import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*; /**
* mock 使用demo
* 一个强大的用于 Java 开发的模拟测试框架
*
* @author tom_plus
* @date 2017-01-02-17:45
*/
public class MockServiceIT extends AbstractServiceIT{
@Mock
SessionContext sessionContext;
@Autowired
private TestService testService;
@Before
public void befTest() {
MockitoAnnotations.initMocks(this);
when(sessionContext.getId()).thenReturn(3);
try {
ReflectionTestUtils.setField(AopTargetUtils.getTarget(testService), "sessionContext", sessionContext);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
@Transactional
public void updateIT() throws Exception {
Teacher teacher = new Teacher();
teacher.settName("樱木花道");
int j = testService.update2(teacher);
System.out.println("result:"+j);
Assert.assertEquals(j,1,"更新成功");
} /**
* 参数匹配器,一旦使用参数匹配器,则方法中必须处处使用参数匹配器
*/
@Test
public void argumentMatcherTest(){
List<String> list = mock(List.class);
when(list.get(anyInt())).thenReturn("hello","world");
String result = list.get(0)+list.get(1);
System.out.println(result);
//verify 方法验证mock 对象的互动次数
verify(list,times(2)).get(anyInt());
verify(list,atLeast(2)).get(anyInt());
Assert.assertEquals("helloworld", result); } /**
* 使用异常处理void 方法
*/
@Test
public void stubbingForVoidMethod() {
List<String> list = mock(List.class);
doThrow(new RuntimeException("you are clear a list!")).when(list).clear();
list.clear();
}
}
package com; import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.aop.framework.AopProxy;
import org.springframework.aop.support.AopUtils; import java.lang.reflect.Field; /**
* Created by tom_plus on 2017/1/2.
*/
public class AopTargetUtils {
/**
* 获取 目标对象
*
* @param proxy 代理对象
* @throws Exception 默认spring中Service对象是代理对象,不能直接把值设置到属性上,所以我们自己写个小的工具类
*/
public static Object getTarget(Object proxy) throws Exception {
if (!AopUtils.isAopProxy(proxy)) {
return proxy;//不是代理对象
}
//jdk
if (AopUtils.isJdkDynamicProxy(proxy)) {
return getJdkDynamicProxyTargetObject(proxy);
} else { //cglib
return getCglibProxyTargetObject(proxy);
}
} private static Object getCglibProxyTargetObject(Object proxy) throws Exception {
Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");//获得字节码文件中的MethodInterceptor cglib$CALLBACK_0 变量
h.setAccessible(true);
Object dynamicAdvisedInterceptor = h.get(proxy);
Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
advised.setAccessible(true);
Object target = ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
return target;
} private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
h.setAccessible(true);
AopProxy aopProxy = (AopProxy) h.get(proxy);
Field advised = aopProxy.getClass().getDeclaredField("advised");
advised.setAccessible(true);
Object target = ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget();
return target;
}
}
mockito使用心得的更多相关文章
- 我的MYSQL学习心得(一) 简单语法
我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(四) 数据类型 我的MYSQL学习心得(五) 运 ...
- NoSql数据库使用半年后在设计上面的一些心得
NoSql数据库这个概念听闻许久了,也陆续看到很多公司和产品都在使用,优缺点似乎都被分析的清清楚楚.但我心里一直存有一个疑惑,它的出现究竟是为了解决什么问题? 这个疑惑非常大,为此我看了很多分析文章, ...
- 我的MYSQL学习心得(二) 数据类型宽度
我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(四) 数据类型 我的MYSQL学习心得(五) 运 ...
- 我的MYSQL学习心得(三) 查看字段长度
我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(四) 数据类型 我的MYSQL学习心得(五) 运 ...
- 我的MYSQL学习心得(四) 数据类型
我的MYSQL学习心得(四) 数据类型 我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(五) 运 ...
- 我的MYSQL学习心得(五) 运算符
我的MYSQL学习心得(五) 运算符 我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(四) 数据 ...
- 我的MYSQL学习心得(六) 函数
我的MYSQL学习心得(六) 函数 我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(四) 数据类 ...
- 我的MYSQL学习心得(七) 查询
我的MYSQL学习心得(七) 查询 我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(四) 数据类 ...
- 我的MYSQL学习心得(八) 插入 更新 删除
我的MYSQL学习心得(八) 插入 更新 删除 我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得( ...
随机推荐
- SpringMVC Controller介绍
SpringMVC Controller 介绍 一.简介 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理 ...
- HTML页面meta标签内容详解
所有的浏览器都支持meta标签,用于提供页面相关信息,信息都是以名(http-equiv和name标示)/值(content标示)对的形式现实. 属性content,用于定义http-equiv(定义 ...
- PHP 版去bom头
原理: 找出文件前3个字符 如果它们对应的ASCII 值分别是 239,187,191 则判断为bom头,去掉前3个字符. 代码实现如下: $basedir = isset($_GET['dir'] ...
- js正则
JS正则 test:判断字符串是否符合规定的正则 rep = /\d+/; rep.test("asdfoiklfasdf89asdfasdf") # true rep = /^\ ...
- MySql: show databases/tables use database desc table
1. show databases mysql> show databases;+--------------------+| Database |+--------------------+| ...
- MediaElement.js之浏览器跨域请求视频播放
浏览器跨域问题一直以来都是作为前端开发人员常见的问题,所以今天学习了下如何使浏览器跨域请求资源 需要了解的知识 -域(主域,子域,什么是跨域) 简单来说由于浏览器同源策略,凡是发送请求url的协议(h ...
- .NET 获取客户端的操作系统版本、浏览器版本和IP地址
我们在使用.NET做网站的时候,很多情况下需要需要知道客户端的操作系统版本和浏览器版本,怎样获取客户端的操作系统和浏览器版本呢?我们可以通过分析UserAgent来获取. .NET 获取客户端的操作系 ...
- (转)Oracle 获取上周一到周末日期的查询sql语句
-- Oracle 取上周一到周末的sql -- 这样取的是 在一周内第几天,是以周日为开始的 select to_char(to_date('20130906','yyyymmdd'),'d') f ...
- C#回顾 - 7.如何使用反射实现工厂模式?
工厂模式是一种比较常用的设计模式,其基本思想在于使用不同的工厂类型来打造不同产品的部件.例如,我们在打造一间屋子时,可能需要窗户.屋顶.门.房梁.柱子等零部件.有的屋子需要很多根柱子,而有的屋子又不需 ...
- ubuntu更新软件源
更新源方法: 1. 打开终端.单击主菜单中的“应用程序 - 附件 - 终端”. 2. 修改更新服务器列表.请在终端中执行下面的两条命令: sudo cp /etc/apt/sources.list / ...