我正在使用Spring MVC 4.1并进行Junits测试。 在上一次测试中,我检查了错误/缺失的参数。 但是我有400个异常,但我希望该异常采用以下格式:code(400),msg,error(参数错误),action。 有人告诉我为此使用@ControllerAdvice,但测试未调用控制器。
checkAccountTest.java
@SuppressWarnings("unused")
@NotNull
private Object[] checkAccount_BadParams_ParametersToTest() {
return new Object[]{
new Object[]{"All params are missing", "", "", HttpStatus.OK, NotBlank.class.getSimpleName()},
new Object[]{"Account is missing", "", regionName, HttpStatus.OK, NotBlank.class.getSimpleName()},
new Object[]{"Region name is missing", "valid@mail.com", "", HttpStatus.OK, NotBlank.class.getSimpleName()},
new Object[]{"Not valid email format", "kukuriku", regionName, HttpStatus.OK, UserNameConstraint.class.getSimpleName()},
new Object[]{"Too short email address", "@c", regionName, HttpStatus.OK, Size.class.getSimpleName()},
new Object[]{"Too short user name", "97", regionName, HttpStatus.OK, Size.class.getSimpleName()},
new Object[]{"Too long user name", new StringBuilder(255), regionName, HttpStatus.OK, Size.class.getSimpleName()}
};
}
@Test
@Parameters(method = "checkAccount_BadParams_ParametersToTest")
@TestCaseName("{0}. Account: {1}, Region: {2}")
public void checkAccount_BadParams_ShouldReturn_HttpStatus400(
String testName,
String account,
String regionName,
HttpStatus expectedStatus,
String customExpectedStatus) throws Exception {
var dto = new CheckAccountRequestDto();
dto.setAccount(account);
dto.setRegionName(regionName);
var result = (ExceptionResult) sendRequest(dto, expectedStatus, SysConstant.PARAM_ERROR);
// assertThat(result.getErrors()).anyMatch(detailedError -> detailedError.ErrorType.equals(customExpectedStatus));
assertThat(result.getError()).isEqualTo(true);
}
ConstraintViolationExceptionResult.java
@JsonRootName(value = "exceptionResult")
@Data
public class ConstraintViolationExceptionResult extends ExceptionResult {
public List<DetailedError> getErrors() {
return errors;
}
public void setErrors(List<DetailedError> errors) {
this.errors = errors;
}
public static class DetailedError{
public String ErrorType;
public String ErrorMessage;
}
private List<DetailedError> errors = new ArrayList<DetailedError>();
public ConstraintViolationExceptionResult() {
}
public ConstraintViolationExceptionResult(Integer code, Object msg, String error, String action) {
super(code, msg, error, action);
}
}
GlobalControllerExceptionHandler.java
@ControllerAdvice
public class GlobalControllerExceptionHandler {
private Logger logger = LoggerFactory.getLogger(GlobalControllerExceptionHandler.class);
@ResponseStatus(value=HttpStatus.OK)
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<ConstraintViolationExceptionResult> handleConflict(ConstraintViolationException e) {
logger.error(e.getMessage(), e);
var d = new Result();
var errorInfo = new ConstraintViolationExceptionResult();
errorInfo.setMsg(e.getMessage());
errorInfo.setCode(SysConstant.PARAM_ERROR);
errorInfo.setError(e.getMessage());
var errors = errorInfo.getErrors();
for (var error : e.getConstraintViolations()) {
var err = new ConstraintViolationExceptionResult.DetailedError();
err.ErrorType = error.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName();
err.ErrorMessage = error.getMessage();
errors.add(err);
}
return new ResponseEntity<ConstraintViolationExceptionResult>(errorInfo, new HttpHeaders(), HttpStatus.OK);
}
}
发送请求功能:
protected ExceptionResult sendRequest(Object dto,
HttpStatus expectedStatus, int customExpectedStatus)
throws JsonProcessingException {
String body = null;
if(dto != null){
var objectMapper = new ObjectMapper();
body = objectMapper.writeValueAsString(dto);
}
var entity = new HttpEntity<>(body, getBaseHttpHeaders());
var response = _restTemplate.postForEntity(get_Url(),
entity,
ExceptionResult.class);
assertThat(response.getStatusCode()).isEqualTo(expectedStatus);
var responseDto = response.getBody();
assertThat(responseDto.getCode()).isEqualTo(customExpectedStatus);
return responseDto;
}