findById 在 Junit 测试用例中返回空

findById returning empty in Junit Test case

我正在使用 junit 测试更新 Employee 方法。这是 junit 代码看起来像

    @RunWith(SpringJUnit4ClassRunner.class)
    public class EmployeeServiceTest {

    @InjectMocks
    EmployeeService service;
    
    @Mock
    EmployeeRepository empRepo;
    
    @Mock
    Employee emp;
    
    @Before
    public void SetupContext() {
        MockitoAnnotations.initMocks(this);
        emp = new Employee(1,"Ankush",4000,"Mumbai");
    }
    
    
    @Test
    public void updateEmployee() throws, Exception {
        when(empRepo.save(emp)).thenReturn(emp);
        EmployeeDTO empDTO=new EmployeeDTO(emp.getId(),"Ankush",4000,"Chennai");
        EmployeeDTO updatedEmp = service.updateEmployee(empDTO);
        assertThat(updatedEmp.getCity().equals("Chennai"));
    }
   }

updateEmployee 服务方法中,我正在接受一项检查

public EmployeeDTO updateEmployee(EmployeeDTO empDTO){
     Optional<Employee> existingemp = empRepo.findById(empDTO.getId());
     if(existingemp.present()){
         //  converting DTO to entity
          empRepo.save(entity); 
      }else{
         throw new EmployeeServiceException("Employee Not Found to update");
      }
    return convertEntityToDto(entity);
 }

为什么 existingemp 总是空的我已经保存了对象 when(empRepo.save(emp)).thenReturn(emp);,其中 emp 只有 ID 1

您不需要模拟 save 方法,因为该方法不会在 updateEmployee 方法中调用。你应该只模拟我们正在为其编写测试用例的实际方法中的依赖方法,所以在这种情况下你需要模拟 findById

when(empRepo.findById(emp.getId()))).thenReturn(Optional.of(emp));
EmployeeDTO empDTO=new EmployeeDTO(emp.getId(),"Ankush",4000,"Chennai");
EmployeeDTO updatedEmp = service.updateEmployee(empDTO);
assertThat(updatedEmp.getCity().equals("Chennai"));
    public EmployeeDTO updateEmployee(EmployeeDTO empDTO){
    Optional<Employee> optionalEmployee = 
    empRepo.findById(empDTO.getId());
    Employee existingEmployee=null;

    if(optionalEmployee.isPresent()){
        existingEmployee=optionalEmployee.get();
    }else{
        throw new EmployeeServiceException("Employee Not Found to update");
    }
    // Use setter to update the fields
    
    return convertEntityToDto(entity);
}