http://www.tuicool.com/articles/J7BFr2A

Mock 测试是单元测试的重要方法之一。Mockito是基于Java的Mock测试框架。
什么是 Mock 测试
Mock 测试就是在测试过程中,对于某些不容易构造(如 HttpServletRequest 必须在Servlet 容器中才能构造出来)或者不容易获取比较复杂的对象(如 JDBC 中的ResultSet 对象),用一个虚拟的对象(Mock 对象)来创建以便测试的测试方法。
Mock可以帮我们把单元测试的耦合分解开,如果代码对另一个类或者接口有依赖,它能够帮我们模拟这些依赖,并帮验证所调用的依赖的行为。
Mock 对象使用范畴
真实对象具有不可确定的行为,产生不可预测的效果,真实对象很难被创建的 真实对象的某些行为很难被触发 真实对象实际上还不存在的(和其他开发小组或者和新的硬件打交道)等等.
示例
1.验证行为
//Let’s import Mockito statically so that the code looks clearer
import static org.mockito.Mockito.*;
//mock creation
List mockedList = mock(List.class);
//using mock object
mockedList.add(“one”);
mockedList.clear();
//verification
verify(mockedList).add(“one”);
verify(mockedList).clear();
一旦创建 mock 将会记得所有的交互。你可以选择验证你感兴趣的任何交互
2.stubbing
//You can mock concrete classes, not just interfaces
LinkedList mockedList = mock(LinkedList.class);
//stubbing
when(mockedList.get(0)).thenReturn(“first”);
when(mockedList.get(1)).thenThrow(new RuntimeException());
//following prints “first”
System.out.println(mockedList.get(0));
//following throws runtime exception
System.out.println(mockedList.get(1));
//following prints “null” because get(999) was not stubbed
System.out.println(mockedList.get(999));
• Stubbing 可以被覆盖。最后的 stubbing 是很重要的
• 一旦 stub,该方法将始终返回一个 stub 的值,无论它有多少次被调用。
3.调用额外的调用数字/at least x / never
//using mock
mockedList.add(“once”);
mockedList.add(“twice”);
mockedList.add(“twice”);
//following two verifications work exactly the same - times(1) is used by default
verify(mockedList).add(“once”);
verify(mockedList, times(1)).add(“once”);
//exact number of invocations verification
verify(mockedList, times(2)).add(“twice”);
//verification using never(). never() is an alias to times(0)
verify(mockedList, never()).add(“never happened”);
times(1) 是默认的,因此,使用的 times(1) 可以显示的省略。
4.Stubbing void 方法处理异常
doThrow(new RuntimeException()).when(mockedList).clear();
//following throws RuntimeException:
mockedList.clear();
5. 标准创建 mock 方式 - 使用 @Mock 注解
最小化可重用 mock 创建代码,使测试类更加可读性,使验证错误更加易读,因为字段名称用于唯一识别 mock
public class ArticleManagerTest {
@Mock private ArticleCalculator calculator;
@Mock private ArticleDatabase database;
在基础类或者测试 runner 里面,使用如下:
MockitoAnnotations.initMocks(testClass);
6. Stubbing 连续调用(迭代器式的 stubbing)
when(mock.someMethod(“some arg”))
.thenReturn(“one”, “two”, “three”);
7. doReturn()|doThrow()| doAnswer()|doNothing()|doCallRealMethod() 家族方法

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐