Search code examples
javaspringjunitjunit4

findById returning empty in Junit Test case


I am testing update Employee method using junit. Here is junit code looks like

    @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"));
    }
   }

Inside updateEmployee service method i am having one check like

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);
 }

Why existingemp is always empty i had already saved the object when(empRepo.save(emp)).thenReturn(emp); where emp have the id 1 only.


Solution

  • You don't need to mock the save method since that method is not called in updateEmployee method. You should only mock the dependent methods inside the actual method for which we are writing test cases, so in this case you need to mock 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"));