Mockito When/Then常见用法

该系列文章翻译自https://www.baeldung.com/mockito-series

接下来我们将以MyList类为例进行介绍

public class MyList extends AbstractList {
 
    @Override
    public String get(final int index) {
        return null;
    }
    @Override
    public int size() {
        return 1;
    }
}

When/Then常见用法常见用法

1.方法一:when().thenReturn()模拟方法的返回

MyList listMock = Mockito.mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false);
 
boolean added = listMock.add(randomAlphabetic(6));
assertThat(added, is(false));

2.方法二:doReturn().when()模拟方法的返回

MyList listMock = Mockito.mock(MyList.class);
doReturn(false).when(listMock).add(anyString());
 
boolean added = listMock.add(randomAlphabetic(6));
assertThat(added, is(false));

3.when().thenThrow()模拟异常(方法返回类型非void)

@Test(expected = IllegalStateException.class)
public void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() {
    MyList listMock = Mockito.mock(MyList.class);
    when(listMock.add(anyString())).thenThrow(IllegalStateException.class);
 
    listMock.add(randomAlphabetic(6));
}

4.doThrow().when()模拟异常(方法返回类型为void)

MyList listMock = Mockito.mock(MyList.class);
doThrow(NullPointerException.class).when(listMock).clear();
 
listMock.clear();

5.模拟方法的多次调用

在下面的例子中,第二次调用add方法会抛出IllegalStateException

MyList listMock = Mockito.mock(MyList.class);
when(listMock.add(anyString()))
  .thenReturn(false)
  .thenThrow(IllegalStateException.class);
 
listMock.add(randomAlphabetic(6));
listMock.add(randomAlphabetic(6)); // will throw the exception

6.spy对象

MyList instance = new MyList();
MyList spy = Mockito.spy(instance);
 
doThrow(NullPointerException.class).when(spy).size();
spy.size(); // will throw the exception

7.使用thenCallRealMethod()调用mock对象的真实方法

MyList listMock = Mockito.mock(MyList.class);
when(listMock.size()).thenCallRealMethod();
 
assertThat(listMock.size(), equalTo(1));

8.doAnswer().when()设置默认返回

MyList listMock = Mockito.mock(MyList.class);
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());
 
String element = listMock.get(1);
assertThat(element, is(equalTo("Always the same")));

你可能感兴趣的:(Mockito When/Then常见用法)