文章目录
使用Mockito模拟异常,以MyDictionary类为例进行介绍
class MyDictionary {
private Map<String, String> wordMap;MyDictionary(){
wordMap = new HashMap<>();}
public voidadd(final String word, final String meaning){
wordMap.put(word, meaning);}
String getMeaning(final String word){return wordMap.get(word);}}
1 Mock对象模拟异常
1.1方法返回类型非void
如果方法的返回类型非void,那么可以使用when().thenThrow()来模拟异常:
@Test(expected = NullPointerException.class)
public voidwhenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown(){
MyDictionary dictMock =mock(MyDictionary.class);when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class);
dictMock.getMeaning("word");}
1.2方法返回类型是void
如果方法返回类型是void,则使用doThrow来模拟异常
@Test(expected = IllegalStateException.class)
public voidwhenConfigVoidRetunMethodToThrowEx_thenExIsThrown(){
MyDictionary dictMock =mock(MyDictionary.class);doThrow(IllegalStateException.class).when(dictMock).add(anyString(),anyString());
dictMock.add("word","meaning");}
1.3模拟异常对象
我们不仅可以在thenThrow()或者doThrow() 中模拟异常类,还可以模拟异常对象。
@Test(expected = NullPointerException.class)
public voidwhenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown(){
MyDictionary dictMock =mock(MyDictionary.class);when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred"));
dictMock.getMeaning("word");}
@Test(expected = IllegalStateException.class)
public voidwhenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown(){
MyDictionary dictMock =mock(MyDictionary.class);doThrow(new IllegalStateException("Error occurred")).when(dictMock).add(anyString(),anyString());
dictMock.add("word","meaning");}
2 Spy对象模拟异常
Spy对象模拟异常的方式与Mock对象相同,如下:
@Test(expected = NullPointerException.class)
public voidgivenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown(){
MyDictionary dict = new MyDictionary();
MyDictionary spy = Mockito.spy(dict);when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class);
spy.getMeaning("word");}
版权归原作者 想要好多offer 所有, 如有侵权,请联系我们删除。