Assertions.assertThrows 不适用于@Mock Annotation

问题描述 投票:0回答:1

我正在尝试测试assertThrows,但是当我使用@Mock Annotation实例化该类时它不起作用。

@ExtendWith(MockitoExtension.class)
class EmployeeMapperTest {

@Mock
private EmployeeMapper employeeMapper;

@Test
@DisplayName("This test will throw NullPointer Exception when DTO is null")
public void should_throw_npe_when_dto_is_null() {
    //given
    CreateEmployeeRequestDTO createEmployeeRequestDTO = null;

    //then
    Exception exp = assertThrows(NullPointerException.class, () -> employeeMapper.dtoToEmployeeEntity(createEmployeeRequestDTO));

    assertEquals("Employee DTO cannot be null", exp.getMessage());
}

}

但是,如果我使用 new EmployeeMapper 而不是 Mock Annotation 实例化映射器类。测试一切正常

private EmployeeMapper employeeMapper = new EmployeeMapper();

在我抛出 NullPointerException 的 EmployMapper 类下面

@Component
public class EmployeeMapper {
    public EmployeeEntity dtoToEmployeeEntity(CreateEmployeeRequestDTO employeeDTO) {
            if(employeeDTO == null) {
                throw new NullPointerException("Employee DTO cannot be null");
            }
            EmployeeEntity entity = new EmployeeEntity();
            entity.setName(employeeDTO.getName());
            entity.setEmail(employeeDTO.getEmail());
            return entity;
        }
}
java spring-boot unit-testing junit mockito
1个回答
0
投票

添加对我有用的答案。它也可能对某人有帮助

我忘记使用 Mockito.when 子句添加返回对象

添加这个,测试成功了

Mockito.when(employeeMapper.dtoToEmployeeEntity(createEmployeeRequestDTO)).thenThrow(new NullPointerException("Employee DTO cannot be null"));

完整的测试如下

    @Test
    @DisplayName("This test will throw NullPointer Exception when DTO is null")
    public void should_throw_npe_when_dto_is_null() {
        //given
        CreateEmployeeRequestDTO createEmployeeRequestDTO = null;

        //when
        Mockito.when(employeeMapper.dtoToEmployeeEntity(createEmployeeRequestDTO)).thenThrow(new NullPointerException("Employee DTO cannot be null"));

        //then
        Exception exp = assertThrows(NullPointerException.class, () -> employeeMapper.dtoToEmployeeEntity(createEmployeeRequestDTO));

        assertEquals("Employee DTO cannot be null", exp.getMessage());
    }
© www.soinside.com 2019 - 2024. All rights reserved.