0

This function tries to retrieve the topic of the GitHub repository name using the GitHub API: https://api.github.com/repos/flutter/flutter/topics

public List<String> getTopics(SearchRepository searchRepository){
        GitHubRequest request = new GitHubRequest();
        List<String> topic_list = new ArrayList<>();
        try {

            String url =  searchRepository.getUrl().split("//")[1].split("github.com")[1];

            request.setUri("/repos"+ 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;
    }

The url returned before string to list conversion is :https://github.com/repouser/reponame

SearchRepository is the v2 model class of Repository from the package: SearchRepositroy As per the earlier suggestions from this wonderful community answers (though the question is now edited, it remains yet relevant) I created the mock test to test the above function as below:

    @Test
    public void getTopicsTest() throws IOException{
        SearchRepository mocksearchRepository = mock(SearchRepository.class);
        GitHubClient mockClient = mock(GitHubClient.class);
        GitHubRequest mockRequest = mock(GitHubRequest.class);
        when(mocksearchRepository.getUrl()).thenReturn("https://github.com/mockuser/mockrepo");
        when(mocksearchRepository.getName()).thenReturn("mockrepo");
        when(mocksearchRepository.getOwner()).thenReturn("mockuser");
        //when(mockRequest.setUri((String) any())).thenReturn(mockRequest.setUri("/repo/mockuser/mockrepo/topics"));
        //The format of the return form is: https://github.com/CyC2018/CS-Notes
        when(mockClient.getStream(any())).thenReturn(topicInputStream());
        //SearchRepository querySearch = new SearchRepository("mockuser","mockrepo");
        List<String> topics = githubServiceMock.getTopics(mocksearchRepository);
        System.out.println(topics);
    }

    private InputStream topicInputStream() {
        String mockTopics = "{" +
                "topic1\": [" +
                "topic2\"," +
                "topic3\"," +
                "skia" +
                "]" +
                "}";
        InputStream stream = new ByteArrayInputStream(mockTopics.getBytes(StandardCharsets.UTF_8));
        System.out.println(stream);
        return stream;
    }

However, I get the 404 internal server error Exception due to the request.setUri(Uri(String)) in the function. Please suggest where I am going wrong.

Test services.GithubServiceTest.getTopicsTest started
java.io.ByteArrayInputStream@6ed99482
org.eclipse.egit.github.core.client.RequestException: Not Found (404)
  | => rat org.eclipse.egit.github.core.client.GitHubClient.createException(GitHubClient.java:552)
        at org.eclipse.egit.github.core.client.GitHubClient.getResponseStream(GitHubClient.java:701)
        at org.eclipse.egit.github.core.client.GitHubClient.getStream(GitHubClient.java:667)
        at services.GithubService.getTopics(GithubService.java:231)
        at services.GithubServiceTest.getTopicsTest(GithubServiceTest.java:222)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
        at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
        at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
        at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
        at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
        at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
        at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
        at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
        at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
        at org.junit.runners.Suite.runChild(Suite.java:128)
        at org.junit.runners.Suite.runChild(Suite.java:27)
        at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
        at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
        at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
        at com.novocode.junit.JUnitRunner$1.execute(JUnitRunner.java:132)
        at sbt.ForkMain$Run.lambda$runTest$1(ForkMain.java:413)
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at java.base/java.lang.Thread.run(Thread.java:834)
[]
[info] Test services.GithubServiceTest.getIssueWordLevelStatisticsTest started
[info] Test services.GithubServiceTest.getRepositoriesByTopicTest started
[info] Test services.GithubServiceTest.getUserDetailsTest started
[info] Test services.GithubServiceTest.getRepositoryDetailsTest started
[info] Test run finished: 0 failed, 0 ignored, 5 total, 1.122s
[error] Failed: Total 10, Failed 1, Errors 0, Passed 9
[error] Failed tests:
[error]         controllers.GithubControllerTest
[error] (Test / test) sbt.TestsFailedException: Tests unsuccessful
6
  • Welcome to Stack Overflow. Please take the tour to learn how Stack Overflow works and read How to Ask on how to improve the quality of your question. Then check the help center to see which questions are on-topic on this site. Please see: Why is “Is it possible to…” a poorly worded question? (don't just change your question to "How").
    – Progman
    Nov 13, 2021 at 10:36
  • I am not sure why you change from one question to other question. It make all current answers don't match the new context. It's better if you can ask new question with new context ....
    – Huy Nguyen
    Nov 16, 2021 at 14:18
  • As far as I can see, you don't use the mocked GithubClient. As a result, the request is actually made to the Github and it returns HTTP 404. Please use a package-level setter for the service object used inside the test so you can override it during the test.
    – Deniz Acay
    Nov 16, 2021 at 15:32
  • Yes! Mocking the client: Nov 16, 2021 at 20:16
  • 1
    It is a mock. @Mock GitHubClient mockClient; InjectMocks GithubService githubServiceMock; With this, it worked! Nov 17, 2021 at 1:44

2 Answers 2

0

You can mock repositoryService and gitHubClient to test various scenarios.

You can provide a package-level setter for these fields. It is a great idea to annotate it with Guava VisibleForTesting annotation.

Then you need to set mocks before the actual test on the instance.

Pseudocode for mocking

// First, we mock repository so we can return it from service
Repository repositoryMock = mock(Repository.class);
when(repository.getUrl()).thenReturn("https://...."); // You can return a URL or String, according to the mocked method's return type

// Then, we mock RepositoryService as well
RepositoryService repositoryServiceMock = mock(RepositoryService.class);
when(repositoryServiceMock.getRepository(anyString(), anyString()).thenReturn(repositoryMock);

// We mock gitHubService similarly
...

// After setting mock on the instance, we call the method and see if the results are expected
List<String> topics = getTopics("...", "...");

assertEquals(topics, ...);

// You can also assert interaction related things
verify(repositoryService).getRepository("a", "b"); // This is OK only if the service is called with "a" and "b" arguments
3
  • 1
    can you provide a bit of pseudocode? Mostly, how to assert on the topic list that this function returns. Thanks Nov 13, 2021 at 7:42
  • Added some pseudocode, please let me know if it needs further clarification!
    – Deniz Acay
    Nov 13, 2021 at 10:43
  • I've modified my question a bit, yet your earlier idea remains relevant. Though I cannot pass the test. Can I tell me where I am going wrong? The jetstream is what I reckon I might be mislading. Thanks Nov 16, 2021 at 6:22
0

First, you need to inject the mock object (repositoryService,gitHubClient) to your function.

If you use spring/spring boot, you can consider to use @Mock and @MockBean annotation. to mock the necessary bean.

The below code to create mock object manually.

RepositoryService fakeRs = Mockito.mock(RepositoryService.class);
GitHubClient fakeGHC = Mockito.mock(GitHubClient.class);

You also can use setter method to set mock object. setRepositoryService(fakeRs); setGitHubClient(fakeGHC);

The other way is using reflection utility to set private object.

ReflectionTestUtils.setField(yourService, "repositoryService", fakeRs);
ReflectionTestUtils.setField(yourService, "gitHubClient", fakeGHC);

After finish ingesting the mock object, you can write an test with expected behavior/data from mock object.

    @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: Don't copy/paste the code, you will get compile errors. I am not using editor tool.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.