简体   繁体   中英

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 parameter... 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?

Instantiate UserService in the initialization method.

You're getting the NPE because UserService is never instantiated. Consider instantiating the variable in the setUp() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM