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

标签 java mockito

我正在为以下代码编写 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());
    }
}

最佳答案

在不检查 StudentDto 的 null 的情况下,您引用了该对象的字段。首先,您需要检查 dto==null ,然后引用 dto 的字段。否则可能会给出异常(exception)。 您的方法 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())));
}

关于java - 如何使用 Mockobject 检查真实对象的空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56679331/

相关文章:

java - Android 中操作栏 setDisplayShowHomeEnabled () 处的 nullpointerException

java - 我正在尝试使用 Mockito 2 模拟最终的 java 类,类被模拟,但我仍然收到未完成的 stub 异常

spring-boot - 如何在 Spring Boot 测试中模拟 BindingResult

java - libgdx 中没有禁用 OpenGL2.0 的选项

java - 一个类的多个实例,加载图像,在java中效率更高

java - 使用静态方法泛型时不兼容的类型

java - 如何测试程序已经退出? [J单元]

java - 如何使用 JProgressBar 运行方法

java - 如何使用 Mockito 从 void 方法中获取值 - Groovy/java

java - 没有使用 mockmvc 的请求映射