mardi 6 avril 2021

Why does my method work in my API, but not in a test class?

I have a problem with unit testing a functionality.


public User[] fetchUserByStarsAscendingOrder(String username) throws IOException {
        User[] user = fetchUser(username);
        Arrays.sort(user,Collections.reverseOrder());
        return user;
    }   

public User[] fetchUser(String username) throws IOException {

        URL url = new URL("https://api.github.com/users/" + username + "/repos");
        InputStreamReader reader = new InputStreamReader(url.openStream());

        User[] user = new Gson().fromJson(reader, User[].class);

        if (user == null) {
            logger.error("No input provided.");
            return null;
        } else {
            logger.info("The output returned.");
            return user;
        }
    }

The above method works just fine in my API, no troubles whatsoever. BUT when I try to use it in my test class, with the same paramater... it suddenly returns null:

class UserServiceTest {

        UserService userService;
        User aUser;
        
        @Test
        void shouldReturnArray() throws IOException {
            //given
            String name = "pjhyett";
            //when
            User[] resultArray = userService.fetchUserByStarsAscendingOrder(name);
            //then
            assertThat(resultArray[0]).isEqualTo(aUser);
        }

        @BeforeEach
        void setUp() {
            aUser = new User();
            aUser.setFull_name("pjhyett/github-services");
            aUser.setDescription("Moved to http://github.com/github/github-services");
            aUser.setClone_url("https://github.com/pjhyett/github-services.git");
            aUser.setStars(408);
            aUser.setCreatedAt("2008-04-28T23:41:21Z");
        }

All the above data is taken from GitHub API and are about public repos. I am reaching for the first element in the array because the method returns a couple of results for the array. IDE tells me that the method that works perfectly in the API itself... returns a null in a test class. Why is that?

Aucun commentaire:

Enregistrer un commentaire