java 如何使用真实的对象的Mockobject检查空值?

ilmyapht  于 2023-06-28  发布在  Java
关注(0)|答案(2)|浏览(142)

我正在为下面的代码编写Mockito,但不知何故,对于null和空检查,它给出了错误。
我如何调试它?

public boolean isValid(StudentDto dto) {
        return (dto.getFirstName().isEmpty() && dto.getlastName().isEmpty() 
                && dto.getEmailId().isEmpty() && dto.getAddress().isEmpty()
                && dto.getPhone().isEmpty() && dto.getCity().isEmpty());
    }

public ResponseEntity<HttpStatus> saveStudent(@Valid StudentDto dto) {
    if(isValid(dto)) {
        log.error(env.getProperty("error.errors"), env.getProperty("error.missing.input.parameters"));
        throw new NotFoundException(env.getProperty("error.missing.input.parameters"), BusinessErrorCode.MISSING_REQUIRED_INPUTS);
    }

    // Convert to entity
    Student student = convertToEntity(dto);

    try {
        studentRepository.save(student);
    } catch (Exception ex) {
        log.error(env.getProperty("error.errors"), env.getProperty("error.db.exception"));
        throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, env.getProperty("error.db.exception"), ex);
    }
    return new ResponseEntity<>(HttpStatus.CREATED);
}

测试类别:

@RunWith(PowerMockRunner.class)
@PrepareForTest({})
public class StudentServiceTest {
    @Rule
    public MockitoRule rule = MockitoJUnit.rule();

    @Mock
    private StudentRepository studentRepositoryMock;

    @InjectMocks
    private StudentService studentService;

    @Mock
    private Student studentMock;

    // Define the Environment as a Mockito mock object
    @Mock 
    private Environment env;

    @Mock
    private StudentDto studentDtoMock;

    List<Student> students = new ArrayList<>();


    // Test case for SaveStudent
    @Test
    public void testSaveStudent() {
        when(divisionService.isValid(studentDtoMock)).thenReturn(true);

        assertEquals(new ResponseEntity<HttpStatus>(HttpStatus.OK).getStatusCode(), 
                divisionService.saveStudent(studentDtoMock).getStatusCode());
    }
}
4uqofj5v

4uqofj5v1#

如果不检查StudentDto的null,则引用此对象的字段。首先,您需要检查dto==null,然后引用dto的字段。否则,它可能会例外。你的方法isValid可以是:

public boolean isValid(StudentDto dto) {
    return (dto==null||((dto.getFirstName().isEmpty() && dto.getlastName().isEmpty() 
            && dto.getEmailId().isEmpty() && dto.getAddress().isEmpty()
            && dto.getPhone().isEmpty() && dto.getCity().isEmpty())));
}
zzzyeukh

zzzyeukh2#

我在下面使用,效果很好。

public boolean isValid(StudentDto dto) {
        return StringUtils.isEmpty(dto);
}

相关问题