Home > Back-end >  AssertionFailedError deleteById
AssertionFailedError deleteById

Time:02-16

I'm new to Junit/Mockito and this is my very first test for employee service class.

I'm wondering if this test of deleteById method does work well.

assertThat(expectedEmployee).isNull(); fails and I become AssertionFailError: Expected: null. Actual: Employee(id=1).

However verify(employeeRepository).deleteById(employee.getId()); works well.

When I'm testig the code with postman, the method works and an employee is deleted.

Employee repository:

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}

Employee service:

public void deleteById(Long id) {
        employeeRepository.deleteById(id);
    } 

Employee controller:

@DeleteMapping("/employees/{id}")
    public void deleteEmployeeById(@PathVariable Long id) {
        employeeManager.deleteById(id);
    }

Test class:

  @ExtendWith(MockitoExtension.class)
    class EmployeeManagerTest {

    @Mock
    private EmployeeRepository employeeRepository;

    @InjectMocks
    private EmployeeManager employeeManager;


@Test
    void shouldDeleteEmployeeById() {
        
        Employee employee = new Employee();
        employee.setId(1L);
                
  when(employeeRepository.findById(employee.getId())).thenReturn(Optional.of(employee));
    
        employeeManager.deleteById(employee.getId());
        
        Employee expectedEmployee = employeeManager.findById(employee.getId()).get();
        
        verify(employeeRepository).deleteById(employee.getId()); -> this works well 
        
       // assertThat(expectedEmployee).isNull(); -> this fails
    }

CodePudding user response:

The assertion fails, because you mocked the method

when(employeeRepository.findById(employee.getId())).thenReturn('something that is not null');

This means, that if you call that method in the test, it will return you the optional with the employee.

  • Related