我在对功能进行单元测试时遇到了问题。
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接口,并与公共回购有关。我要访问数组中的第一个元素,因为该方法返回了数组的几个结果。
IDE告诉我,在API本身中完美工作的方法...在测试类中返回null。
为什么会这样呢?
发布于 2021-04-07 14:50:01
在初始化方法中实例化 UserService 。
你会得到NPE,因为UserService从未被实例化过。考虑实例化setUp()方法中的变量。
https://stackoverflow.com/questions/66970226
复制相似问题