问题描述
我正在使用 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(),"Chennai");
EmployeeDTO updatedEmp = service.updateEmployee(empDTO);
assertthat(updatedEmp.getCity().equals("Chennai"));
}
}
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);
}