java mock框架 —— Mcktio

Mock的定义

在面向对象程序设计中,模拟对象是以可控的方式模拟真实对象行为的假对象

为什么使用Mock

在单元测试中,模拟对象可以模拟复杂的、真实的对象的行为,如果真实的对象无法放入单元测试中,可以使用模拟对象。

测试驱动的开发(TDD)要求我们先写单元测试,在写实现代码,在写单元测试的过程中,我们往往会遇到要测试的类有很多依赖,这些依赖的类型、对象、资源又有别的依赖,从而形成一个大的依赖树,要在单元测试的环境中完整的构建这样的依赖,是一件很困难事情,A < B > C, 我们要测试B就需要mockAC 

Mocktio是什么

mocktio是mock框架,可以用简洁的API做测试

使用Mocktio

maven

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.23.4</version>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13-beta-1</version>
</dependency>

gradle

compile("org.mockito:mockito-core:2.23.4")

1. 验证行为

 //Let's import Mockito statically so that the code looks clearer
 import static org.mockito.Mockito.*;

 //模拟List对象
 List mockedList = mock(List.class);

 //模拟一些行为
 mockedList.add("one");
 mockedList.clear();

 //验证行为是否发生
 verify(mockedList).add("one");
 verify(mockedList).clear();

2. 模拟期望结果

 LinkedList mockedList = mock(LinkedList.class);

 // 打桩
 when(mockedList.get(0)).thenReturn("first");
 when(mockedList.get(1)).thenThrow(new RuntimeException());

 // 输出first
 System.out.println(mockedList.get(0));

 //throws runtime exception
 System.out.println(mockedList.get(1));

 // 输出null
 System.out.println(mockedList.get(999));

 //Although it is possible to verify a stubbed invocation, usually it's just redundant
 //If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).
 //If your code doesn't care what get(0) returns, then it should not be stubbed. Not convinced? See here.
 verify(mockedList).get(0);

未完待续……

猜你喜欢

转载自www.cnblogs.com/dawangele/p/10324295.html