gson 为什么我的方法可以在我的API中工作,而不能在测试类中工作?

z9gpfhce  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(168)

我在对功能进行单元测试时遇到问题。

  1. public User[] fetchUserByStarsAscendingOrder(String username) throws IOException {
  2. User[] user = fetchUser(username);
  3. Arrays.sort(user,Collections.reverseOrder());
  4. return user;
  5. }
  6. public User[] fetchUser(String username) throws IOException {
  7. URL url = new URL("https://api.github.com/users/" + username + "/repos");
  8. InputStreamReader reader = new InputStreamReader(url.openStream());
  9. User[] user = new Gson().fromJson(reader, User[].class);
  10. if (user == null) {
  11. logger.error("No input provided.");
  12. return null;
  13. } else {
  14. logger.info("The output returned.");
  15. return user;
  16. }
  17. }

上面的方法在我的API中运行得很好,没有任何问题。
但是当我尝试在我的测试类中使用它时,使用相同的参数......它突然返回null:

  1. class UserServiceTest {
  2. UserService userService;
  3. User aUser;
  4. @Test
  5. void shouldReturnArray() throws IOException {
  6. //given
  7. String name = "pjhyett";
  8. //when
  9. User[] resultArray = userService.fetchUserByStarsAscendingOrder(name);
  10. //then
  11. assertThat(resultArray[0]).isEqualTo(aUser);
  12. }
  13. @BeforeEach
  14. void setUp() {
  15. aUser = new User();
  16. aUser.setFull_name("pjhyett/github-services");
  17. aUser.setDescription("Moved to http://github.com/github/github-services");
  18. aUser.setClone_url("https://github.com/pjhyett/github-services.git");
  19. aUser.setStars(408);
  20. aUser.setCreatedAt("2008-04-28T23:41:21Z");
  21. }

以上所有数据都是从GitHub API中获取的,并且都是关于公共存储库的。我将访问数组中的第一个元素,因为该方法返回数组的几个结果。
IDE告诉我,在API本身中完美工作的方法...在测试类中返回空值。
为什么会这样呢?

wz1wpwve

wz1wpwve1#

在初始化方法中示例化UserService

因为UserService从未示例化,所以您将得到NPE。请考虑在setUp()方法中示例化变量。

相关问题