Mockito.when是一種Mockito框架中的方法,它可以用于模擬返回值和異常。該方法接受一個(gè)方法調(diào)用作為參數(shù),然后可以使用鏈?zhǔn)秸{(diào)用來(lái)模擬方法的返回值或拋出一個(gè)異常。
一、Mockito.when的基本語(yǔ)法
Mockito.when的語(yǔ)法格式如下:
when(mock.method()).thenReturn(value);
// or
when(mock.method()).thenThrow(exception);
在這里,mock是被模擬的對(duì)象,method是被模擬的方法,value是模擬的返回值,exception是模擬的異常。
使用Mockito.when時(shí),必須先創(chuàng)建一個(gè)mock對(duì)象,并指定它模擬哪個(gè)類或接口。例如:
SomeInterface mock = Mockito.mock(SomeInterface.class);
這將創(chuàng)建一個(gè)模擬SomeInterface接口的mock對(duì)象。然后,就可以使用Mockito.when來(lái)模擬該接口的方法了。
二、Mockito.when的鏈?zhǔn)秸{(diào)用
使用Mockito.when的另一個(gè)強(qiáng)大功能是鏈?zhǔn)秸{(diào)用。鏈?zhǔn)秸{(diào)用允許我們按方法的順序指定模擬的返回值或異常。
下面是一個(gè)簡(jiǎn)單的例子,它演示了如何使用Mockito.when和鏈?zhǔn)秸{(diào)用來(lái)模擬一個(gè)方法的返回值:
when(mock.getValue()).thenReturn("hello").thenReturn("world");
String first = mock.getValue(); // returns "hello"
String second = mock.getValue(); // returns "world"
在這個(gè)例子中,我們使用了兩個(gè)thenReturn方法來(lái)指定兩個(gè)不同的返回值。我們首先指定返回值為"hello",然后指定返回值為"world"。
當(dāng)我們使用mock.getValue()方法時(shí),Mockito會(huì)注意到我們使用了兩個(gè)thenReturn方法,并依次返回它們。第一次調(diào)用時(shí),返回值為"hello",第二次調(diào)用時(shí),返回值為"world"。
三、Mockito.when的參數(shù)匹配器
Mockito.when還提供了參數(shù)匹配器的功能。參數(shù)匹配器允許您指定對(duì)于某些參數(shù),Mockito應(yīng)該如何模擬方法的行為。
下面是一個(gè)例子,它演示了如何使用參數(shù)匹配器:
when(mock.someMethod(anyInt(), eq("test"))).thenReturn("result");
String result = mock.someMethod(1, "test"); // returns "result"
在這個(gè)例子中,我們指定了一個(gè)參數(shù)匹配器anyInt()和一個(gè)參數(shù)匹配器eq("test")。anyInt()匹配任何整數(shù)值,eq("test")匹配"test"字符串。
當(dāng)我們調(diào)用mock.someMethod(1, "test")方法時(shí),Mockito會(huì)首先檢查第一個(gè)參數(shù)是否為任何整數(shù)值(由anyInt() 匹配),然后檢查第二個(gè)參數(shù)是否等于"test"字符串(由eq("test")匹配),如果兩個(gè)參數(shù)都匹配,則返回"result"字符串。
四、Mockito.when的異常模擬
Mockito.when還可以用于模擬方法拋出異常的情況。你可以使用Mockito.when和thenThrow方法來(lái)模擬異常:
when(mock.someMethod()).thenThrow(new Exception());
mock.someMethod(); // throws Exception
在這個(gè)例子中,我們使用Mockito.when和thenThrow方法來(lái)模擬模擬方法拋出異常。在我們調(diào)用mock.someMethod()方法的時(shí)候,它將拋出一個(gè)Exception異常。
五、總結(jié)
在本文中,我們學(xué)習(xí)了Mockito.when的基本語(yǔ)法、鏈?zhǔn)秸{(diào)用、參數(shù)匹配器和異常模擬。Mockito.when是Mockito框架中最常用的方法之一,它允許我們使用簡(jiǎn)單、有效的語(yǔ)法模擬方法的行為。
下面是學(xué)習(xí)Mockito.when的完整示例代碼:
public class MockExample {
public static void main(String[] args) {
// 創(chuàng)建Mock對(duì)象
SomeInterface mock = Mockito.mock(SomeInterface.class);
// 模擬返回值
when(mock.getValue()).thenReturn("hello").thenReturn("world");
String first = mock.getValue(); // returns "hello"
String second = mock.getValue(); // returns "world"
// 參數(shù)匹配器
when(mock.someMethod(anyInt(), eq("test"))).thenReturn("result");
String result = mock.someMethod(1, "test"); // returns "result"
// 異常模擬
when(mock.someMethod()).thenThrow(new Exception());
try {
mock.someMethod(); // throws Exception
} catch (Exception e) {
// Handle Exception
}
}
}
public interface SomeInterface {
String getValue();
String someMethod(int num, String str) throws Exception;
}