运行环境Android studio
Mockito的一些常用功能
验证测试中的某些行为
//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,times(1)).add("one");
verify(mockedList).clear();
当我们添加这些代码时,单元测试输出控制台不会有输出,显示状态也是:
一旦Mock对象被创建了,Mock就会记录我们队Mock的操作,例如我们写了mockedList.add("one");
之后调用verify(mockedList).add("one"); 就说明我们执行了一次mockedList.add("one")语句,
** 后续我们会详细介绍verify函数 **
添加测试桩(Stub)
//You can mock concrete classes, not just interfaces(你可以mock具体的类型,不仅只是接口)
//List是接口 LinkedList是具体的类型
LinkedList mockedList = mock(LinkedList.class);
//stubbing 测试桩,在调用get(0)时返回"first"
when(mockedList.get(0)).thenReturn("first");
//stubbing 测试桩,在调用get(1)时抛出异常
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));