2016-12-06 109 views
0

我有以下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.

如何使我的方法可測試?

+2

你需要改變你的'MyRestService'代碼,讓依賴注入,基本上 - 我們的'RestClient'是依賴那裏。 –

+0

您是否將模擬'restClient'注入到'myService'模擬中?無論如何,你違反黑盒測試原則。最好爲'RestClient'編寫一個單獨的測試,imho。 – vikingsteve

+0

您的代碼不會使用您的RestClient的模擬版本,因爲您創建了它的新實例 – user7

回答

1

你的SUT應該是這樣的

class YourClass { 
    @Inject 
    private RestClient restClient; //Injecting RestClient 

    public Address getOfficeLocation(String id){ 
     String url = String.format(officeAddress, id); 
     JSONObject jsonObject = restClient.get(url, null, credentials); 
     return AddressParser.parseOfficeAddress(jsonObject); 
    } 
} 

而且你的測試代碼已經

@Mock 
private MyRestService myService; 

我相信MyRestService正在測試(SUT)的系統,因此它不應該被嘲笑而是必須創建它的新對象

也許類似於

@InjectMocks 
private MyRestService myService; 

這將注入嘲笑RestClientMyRestService

+0

它可能*應該*,因爲DI/IoC還有其他好處以及測試,但它不是*必須* 。 –

+0

@DaveNewton我同意。但是從OP的測試代碼來看,它(RestClient)是一個被注入的對象。 – user7

+0

是的,正如多個註釋中提到的那樣。但是你仍然可以使用Mockito原樣測試代碼。 –