【发布时间】:2021-02-22 12:19:55
【问题描述】:
我有以下方法和 Junit 用于我需要为其编写 Junit 的方法。
Employee POJO 类看起来像
public class Employee {
String id ;
Department department; //another simple pojo class
Junit 失败并出现以下 NPE 错误 s.getDepartment() 评估为 null。我该如何避免它
java.lang.NullPointerException at com.example.mockito.TodoService.lambda$0(TodoService.java:47) at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195) at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655)
void fetch(String date)
{
List<Employee> employeeList = todoRepository.call(date);
employeeList= employeeList
.stream()
.map(s -> {
System.out.println("in here map s.getDepartment() " + s.getDepartment());//prints null in junit
s.getDepartment().setDeptName("CSE");
return s;
} ).collect(Collectors.toList());
下面是Junit
@ExtendWith(MockitoExtension.class)
public class TodoServiceTest {
@InjectMocks
private TodoService todoService;
@Mock
private TodoRepository todoRepository;
private List<TodosObject> actualList;
@Test
public void lambda() {
String date = "2021";
List<Employee> list = new ArrayList<>();
Employee e = new Employee();
list.add(e);
when(todoRepository.call(date)).thenReturn(list);
todoService.fetch(date);
}
【问题讨论】:
-
在您提供的 POJO 中,您似乎没有创建 getter/setter。您是否无论如何创建这些并使用它们来设置员工的价值观?否则 NPE 是合乎逻辑的。
-
为简洁起见,我在示例中创建了刚刚省略的示例。@Wouter van der Linde 给出的答案解决了问题
标签: java unit-testing junit mocking