我在对功能进行单元测试时遇到问题。
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;
}
}
上面的方法在我的API中运行得很好,没有任何问题。
但是当我尝试在我的测试类中使用它时,使用相同的参数......它突然返回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");
}
以上所有数据都是从GitHub API中获取的,并且都是关于公共存储库的。我将访问数组中的第一个元素,因为该方法返回数组的几个结果。
IDE告诉我,在API本身中完美工作的方法...在测试类中返回空值。
为什么会这样呢?
1条答案
按热度按时间wz1wpwve1#
在初始化方法中示例化
UserService
。因为
UserService
从未示例化,所以您将得到NPE。请考虑在setUp()
方法中示例化变量。