好了,代码可以改进,使其实际检验的......
目前,没有编写代码的单元测试真的很好的方式,因为构造没有任何机会创建一个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吗?这将非常有帮助。我被困在这里非常糟糕。 –
根据您的代码添加了一些其他示例。 –