好了,代碼可以改進,使其實際檢驗的......
目前,沒有編寫代碼的單元測試真的很好的方式,因爲構造沒有任何機會創建一個JasperserverRestClient改變它。您至少可以添加另一個構造函數(可能是包訪問)以允許使用另一個JasperserverRestClient。 (另外,您可以考慮使用工廠模式。但是,這可能是複雜的。)
然後,你可以嘲笑那個......
JasperserverRestClient jasperServerClient = Mockito.mock(JasperserverRestClient.class);
RestClientSession session = Mockito.mock(RestClientSession.class);
Mockito.when(jasperServerClient.authenticate("x", "y")).thenReturn(session);
RepositoryClient repositoryClient = new RepositoryClient(jasperServerClient);
這至少可以讓你進行測試,進行身份驗證是通過Mockito.verify
用正確的參數調用。
此外,它可以讓你測試listTemplates
方法調用會議與正確的參數(當然,你需要更多的嘲笑那裏)。
另外一個構造函數,假設你的測試是在同一個包,應該是這樣的:
RepositoryClient(JasperserverRestClient httpRestClient, JasperServerInfo serverInfo) {
this.info = serverInfo;
this.httpRestClient = httpRestClient;
try {
restClientSession = httpRestClient.authenticate(info.username.trim(), info.password.trim());
}
catch (Exception e) {
INodeProcessor.logger.warn(e.toString());
throw Error.REPOSITORY_CLIENT_ERROR.with();
}
}
這樣你可以注入你的JasperserverRestClient的嘲笑實例到你的對象。
您listTemplates法會(addtionally)看起來像這樣的測試...
X resourcesService = Mockito.mock(X.class); // No clue what the resourcesService() method is supposed to return, fill that in here
Mockito.when (restClientSession.resourcesService()).thenReturn (resourcesService);
...這將允許部分restClientSession.resourcesService()
工作。下一步...
Y resources = Mockito.mock(Y.class); // Same thing here, don't know what resources() should return, insert that class here
Mockito.when(resourcesService.resources()).thenReturn (resources);
這將允許resources()
調用工作。
接下來我們做一些掛羊頭賣狗肉:
Mockito.when(resources.parameter(Mockito.anyString(),Mockito.anyString())thenReturn(資源); //假設ResourceSearchParameter常量是一個字符串
。
這將使參數()調用通過返回相同的資源()對象的工作。
等等......你需要的時候(...)。thenReturn(...)的搜索方法返回OperationResult<ClientResourceListWrapper>
等,但這與上面的內容相同。
最後,我們可以驗證這些方法是用正確的參數調用的。
Mockito.verify(resources, Mockito.times(1)).parameter(ResourceSearchParameter.FOLDER_URI, info.reportDirectory);
Mockito.verify(resources, Mockito.times(1)).parameter(ResourceSearchParameter.RECURSIVE, "false"
Mockito.verify(resources, Mockito.times(1)).search();
謝謝弗洛裏安您的寶貴意見。 –
你能幫我創建構造函數和listTemplates嗎?這將非常有幫助。我被困在這裏非常糟糕。 –
根據您的代碼添加了一些其他示例。 –