Mockito When/Then常見用法

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

接下來(lái)我們將以MyList類為例進(jìn)行介紹

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.模擬方法的多次調(diào)用

在下面的例子中,第二次調(diào)用add方法會(huì)拋出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對(duì)象

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

7.使用thenCallRealMethod()調(diào)用mock對(duì)象的真實(shí)方法

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

8.doAnswer().when()設(shè)置默認(rèn)返回

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")));
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容