如何解决findById 在 Junit 测试用例中返回空
我正在使用 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);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。