[英]Can anyone suggest a mockito Test for this code?
此函数尝试使用 GitHub API 检索 GitHub 存储库名称的主题: https : //api.github.com/repos/flutter/flutter/topics
public List<String> getTopics(String user, String repo){
GitHubRequest request = new GitHubRequest();
List<String> topic_list = new ArrayList<>();
try {
Repository repository = repositoryService.getRepository(user,repo);
String url = repository.getUrl().split("//")[1].split("api.github.com")[1];
request.setUri(url + "/topics");
String result = new BufferedReader(new InputStreamReader(gitHubClient.getStream(request)))
.lines().collect(Collectors.joining("\n"));
JSONObject jsonObject = new JSONObject(result);
topic_list = Arrays.stream(jsonObject.get("names").toString().replace("[", "").replace("]", "").split(",")).collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
return topic_list;
}
有没有办法为此编写一个模拟测试用例? 初学者测试,谢谢!
您可以模拟repositoryService
和gitHubClient
来测试各种场景。
您可以为这些字段提供包级设置器。 使用 Guava VisibleForTesting注释来注释它是一个好主意。
然后您需要在对实例进行实际测试之前设置模拟。
首先,您需要将模拟对象 (repositoryService,gitHubClient) 注入您的函数。
如果使用spring/spring boot,可以考虑使用@Mock和@MockBean注解。 模拟必要的bean。
下面的代码手动创建模拟对象。
RepositoryService fakeRs = Mockito.mock(RepositoryService.class);
GitHubClient fakeGHC = Mockito.mock(GitHubClient.class);
您也可以使用 setter 方法来设置模拟对象。 setRepositoryService(fakeRs); setGitHubClient(fakeGHC);
另一种方法是使用反射实用程序来设置私有对象。
ReflectionTestUtils.setField(yourService, "repositoryService", fakeRs);
ReflectionTestUtils.setField(yourService, "gitHubClient", fakeGHC);
完成摄取模拟对象后,您可以使用模拟对象的预期行为/数据编写测试。
@Test
public void testGetTopics(){
// init mock object code in case setter/getter/reflection utils
Repository expectedRepository = createExampleRepository();
Mockito.when(repositoryService.getRepository(Mockito.anyString(),Mockito.anyString())
.thenReturn(expectedRepository);
// continue to fake gitHubClient with your expected data/ exceptions...
//call your method
List<?> data = yourService.getTopic("user","data");
Assertions.assertTrue(data!=null);
// you can write few assertion base on your fake datas
}
PS:不要复制/粘贴代码,你会得到编译错误。 我没有使用编辑器工具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.