Mockito When/Then常见用法
该系列文章翻译自https://www.baeldung.com/mockito-series
接下来我们将以MyList类为例进行介绍
public class MyList extends AbstractList<String> {
@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")));
标签:
java
, spring boot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)