我有以下MyRestService
類的方法,測試方法:的Mockito:僅使用局部變量
public Address getOfficeLocation(String id){
RestClient restClient = new RestClient(tokenOauthUrl);
String url = String.format(officeAddress, id);
JSONObject jsonObject = restClient.get(url, null, credentials);
return AddressParser.parseOfficeAddress(jsonObject);
}
我想restClient.get
被調用。我寫了下面的測試:
@Mock
private MyRestService myService;
@Mock
private RestClient restClient;
@Test
public void getOfficeLocationTest(){
myService.getOfficeLocation(any(String.class));
Mockito.verify(restClient, Mockito.times(1)).get(any(String.class), any(MultivaluedMap.class), any(Credentials.class));
}
我想這是非常錯誤的做法。我得到測試失敗:Wanted but not invoked: Actually, there were zero interactions with this mock.
如何使我的方法可測試?
你需要改變你的'MyRestService'代碼,讓依賴注入,基本上 - 我們的'RestClient'是依賴那裏。 –
您是否將模擬'restClient'注入到'myService'模擬中?無論如何,你違反黑盒測試原則。最好爲'RestClient'編寫一個單獨的測試,imho。 – vikingsteve
您的代碼不會使用您的RestClient的模擬版本,因爲您創建了它的新實例 – user7