我正在尝试测试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;
}
}
添加对我有用的答案。它也可能对某人有帮助
我忘记使用 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());
}