Mockito最大的特点是模拟依赖,
添加依赖
testImplementation "org.mockito:mockito-core:2.11.0"
1. 四种Mock方式
-
使用mock方法
@Test public void test(){ Calculator calculator=mock(Calculator.class);//使用mock方法 Assert.assertNotNull(calculator); }
-
使用@Mock注解
@Mock Calculator calculator; @Before public void setup(){ MockitoAnnotations.initMocks(this);//初始化 } @Test public void test1(){ Assert.assertNotNull(calculator); }
在使用注解之前要调用
MockitoAnnotations.initMocks(this);
来初始化mock -
运行器方式
@RunWith(MockitoJUnitRunner.class)//使用MockitoJUnitRunner运行器 public class MockTest { @Mock Calculator calculator; @Test public void test2(){ Assert.assertNotNull(calculator); } }
-
MockitoRule方法
@Mock Calculator calculator; @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Test public void test3(){ Assert.assertNotNull(calculator); }
2. 常用打桩方法
打桩的意思是对mock出来的对象进行操作,比如模拟返回值
方法名 | 方法描述 |
---|---|
thenReturn(T value) | 设置要返回的值 |
thenThrow(Throwable… throwables) | thenThrow(Throwable… throwables) |
thenAnswer(Answer<?> answer) | 对结果进行拦截 |
doReturn(Object toBeReturned) | 提前设置要返回的值 |
doThrow(Throwable… toBeThrown) | 提前设置要抛出的异常 |
doAnswer(Answer answer) | 提前对结果进行拦截 |
doCallRealMethod() | 调用某一个方法的真实实现 |
doNothing() | 设置void方法什么也不做 |
比如
Calculator文件有方法
public String getMyName(){
return "leory";
}
通过单元测试可以模拟更改返回值
when(calculator.getMyName()).thenReturn("hello,leory");
System.out.print(calculator.getMyName());
输出hello,leory
doReturn主要是对无法用thenReturn的情况,比如返回值void
doReturn("小明").when(calculator).getMyName();
System.out.print(calculator.getMyName());
输出 小明
3. 常用验证方法
上面所说的都是状态测试,所关心的是返回结果,但如果关心方法是否被正确的参数调用过,这时候就要调用验证方法了
通过verify(T mock)
验证发生的某些行为 。
方法名 | 方法描述 |
---|---|
after(long millis) | 一段时间后再验证 |
timeout(long millis) | 验证方法执行是否超时 |
atLeast(int minNumberOfInvocations) | 至少执行多少次 |
atMost(int maxNumberOfInvocations) | 至多进行n次验证 |
description(String description) | 验证失败时输出的内容 |
times(int wantedNumberOfInvocations) | 验证调用方法的次数 |
never() | 验证交互没有发生,相当于times(0) |
only() | 验证方法只被调用一次,相当于times(1) |
4. 常用参数匹配器
方法名 | 方法描述 |
---|---|
anyObject() | 匹配任何对象 |
any(Class<T> type) | 与anyObject()一样 |
any() | 与anyObject()一样 |
anyBoolean() | 匹配任何boolean和非空Boolean |
anyByte() | 匹配任何byte和非空Byte |
anyCollection() | 匹配任何非空Collection |
anyDouble() | 匹配任何double和非空Double |
anyFloat() | 匹配任何double和非空Double |
anyInt() | 匹配任何int和非空Integer |
anyList() | 匹配任何非空List |
anyLong() | 匹配任何long和非空Long |
anyMap() | 匹配任何非空Map |
anyString() | 匹配任何非空String |
contains(String substring) | 参数包含给定的substring字符串 |
argThat(ArgumentMatcher <T> matcher) | 创建自定义的参数匹配模式 |
举个栗子
参数为aynInt()
@Test
public void test5(){
when(calculator.add(anyInt(),anyInt())).thenReturn(100);
Assert.assertEquals(100,calculator.add(1,2));
}
参数包含某个string
@Test
public void test5(){
when(calculator.judgeInput(contains("朱"))).thenReturn("朱");
Assert.assertEquals("小朱",calculator.judgeInput("小朱"));
}
5. 其他方法
方法名 | 方法描述 |
---|---|
reset(T … mocks) | 重置Mock |
spy(Class<T> classToSpy) | 实现调用真实对象的实现 |
inOrder(Object… mocks) | 验证执行顺序 |
@InjectMocks注解 | 自动将模拟对象注入到被测试对象中 |
网友评论