AssertionFailedError deleteById

AssertionFailedError deleteById

我是 Junit/Mockito 的新手,这是我对员工服务的第一次测试 class。

我想知道这个 deleteById 方法的测试是否有效。

assertThat(expectedEmployee).isNull(); 失败并显示消息:

AssertionFailError: 
Expected: null. Actual: Employee(id=1). 

不过 verify(employeeRepository).deleteById(employee.getId()); 效果很好。

当我使用 postman 测试代码时,该方法有效并且删除了一名员工。

员工资料库:

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

员工服务:

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

员工控制器:

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

测试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
        }

断言失败,因为你模拟了方法

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

这意味着,如果您在测试中调用该方法,它将 return 您与员工的可选。