带有 lambda 和流图的 Junit

Junit with lambdas and stream map

我有下面的方法和 Junit,我需要为该方法编写 Junit。

Employee POJO class 看起来像

public class Employee {
    
    String id ;
    
    Department department; //another simple pojo class

Junit 失败并出现以下 NPE 错误 s.getDepartment() 计算结果为 null.How 我可以避免吗

java.lang.NullPointerException
  at com.example.mockito.TodoService.lambda[=11=](TodoService.java:47)
  at java.base/java.util.stream.ReferencePipeline.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);

}

需要在lambda()方法中设置Department的值

lambda() 你做的:

List<Employee> list = new ArrayList<>();
Employee e = new Employee();
list.add(e);

没有设置 Department 的值。然后在 fetch() 你做 s.getDepartment().setDeptName("CSE"); 这会产生一个 NPE。

您需要在 lambda() 方法中设置部门(例如 e.setDepartment(new Department()) 或类似的东西)或在 fetch() 方法中检查 null,具体取决于您的用例。 (例如,department 可以在生产中为 null 吗?)