我有验证者的课程。
@Component("beforeCreateLanguageDtoValidator")
public class LanguageDtoValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return LanguageDto.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
//some logic validator
}
}
以及使用此验证器的服务层中的方法。
public boolean isValid(LanguageDto dto) {
DataBinder dataBinder = new DataBinder(dto);
dataBinder.addValidators(languageDtoValidator);
dataBinder.validate(dto);
if (dataBinder.getBindingResult().hasErrors()) {
String errorsMessage = dataBinder.getBindingResult().getAllErrors().stream().
map(e -> messageSource.getMessage(e, Locale.getDefault()))
.collect(Collectors.joining("\n"));
throw new LanguageNameNotValidException(errorsMessage);
}
return true;
}
我不明白,我们是如何测试这种方法的。我已经写了两个测试,但它们都不起作用。
@Test
void shouldGetTrueWhenDtoIsValid() {
//when
doNothing().when(dataBinder).addValidators(languageDtoValidator);
doNothing().when(dataBinder).validate(dto);
when(dataBinder.getBindingResult().hasErrors()).thenReturn(false);
boolean result = languageService.isValid(dto);
//than
assertThat(result).isEqualTo(true);
verify(dataBinder, times(1)).getBindingResult().hasErrors();
verify(dataBinder, times(1)).addValidators(languageDtoValidator);
verify(dataBinder, times(1)).validate(dto);
}
@Test
void shouldGetThrowExceptionWhenDtoIsNotValid() {
//when
doNothing().when(dataBinder).addValidators(languageDtoValidator);
doNothing().when(dataBinder).validate(dto);
when(dataBinder.getBindingResult().hasErrors()).thenReturn(true);
//than
verify(dataBinder, times(1)).getBindingResult().hasErrors();
verify(dataBinder, times(1)).addValidators(languageDtoValidator);
verify(dataBinder, times(1)).validate(dto);
assertThatThrownBy(() -> languageService.isValid(dto))
.isInstanceOf(LanguageNameNotValidException.class);
}
当我在这里捕获 NPE 时:
`when(dataBinder.getBindingResult().hasErrors()).thenReturn(false);
at com.springCrudV2.demo.service.LanguageServiceTest.shouldGetThrowExceptionWhenDtoIsNotValid`
你能建议我解决这个问题吗?