gpt4 book ai didi

java - 包含测试失败 Java 的列表

转载 作者:行者123 更新时间:2023-12-02 01:58:49 25 4
gpt4 key购买 nike

我在测试方法 (displayEmployees) 时遇到问题,该方法返回对象的列表

public class Task {
static List<Employee> employeeList;

public static void main(String[] args) {
Employee employee1 = new Employee("Dobrobaba", "Irina", "Ivanovna",
"Moskva", 1900, 6);
Employee employee2 = new Employee("Shmal", "Anna", "Nikolaevna",
"Krasnodar", 2017, 8);
Employee employee3 = new Employee("Kerimova", "Niseimhalum", "Magomedmirzaevna",
"New-York", 2017, 3);
Employee employee4 = new Employee("Dobryden", "Yuri", "Viktorovich",
"Auckland", 2014, 11);
Employee employee5 = new Employee("Lopata", "Leonid", "Nikolaevich",
"Beijing", 2014, 11);
employeeList = new ArrayList<>(Arrays.asList(employee1, employee2, employee3, employee4, employee5));
}

/**
* Prints employees' information, which have worked more than 'n' year(s) for now.
*
* @param n years quantity
*/
public static List<Object> displayEmployees(int n) {
List<Employee> requiredList = new ArrayList<>();
employeeList.forEach(employee -> {
if (Year.now().getValue() - employee.getEmploymentYear() >= n) {
requiredList.add(employee);
}
});
return Collections.singletonList(requiredList);
}
}

这就是我尝试进行测试的方式,将两个列表相互进行比较:

public class TaskTest {
public static void main(String[] args) {
displayEmployeesTest();
}

public static void assertEquals(String testName, List<Object> expected, List<Object> actual) {
if (expected.equals(actual)) {
System.out.println(testName + " passed");
} else {
System.out.println(testName + " failed: expected " + expected + ", actual " + actual);
}
}

private static void displayEmployeesTest() {
List<Object> expectedList;
Employee employee1 = new Employee("Dobrobaba", "Irina", "Ivanovna",
"Moskva", 1900, 6);
Employee employee2 = new Employee("Shmal", "Anna", "Nikolaevna",
"Krasnodar", 2017, 8);
Employee employee3 = new Employee("Kerimova", "Niseimhalum", "Magomedmirzaevna",
"New-York", 2017, 3);
Employee employee4 = new Employee("Dobryden", "Yuri", "Viktorovich",
"Auckland", 2014, 11);
Employee employee5 = new Employee("Lopata", "Leonid", "Nikolaevich",
"Beijing", 2014, 11);
expectedList = new ArrayList<>(Arrays.asList(employee1, employee4, employee5));

assertEquals("displayEmployeesTest", expectedList, displayEmployees(3));
}
}

问题是 - 我在运行 TaskTest 时收到错误“java.lang.NullPointerException”

出现这个错误的原因是什么?感谢您的关注!

最佳答案

您调用 Task.displayEmployees 而不调用 Task.main,因此 Task 中的 employeeList 字段永远不会初始化

关于java - 包含测试失败 Java 的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51918226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com