我有以下控制器方法
@PostMapping(consumes = "application/json",
produces = "application/json")
public ResponseEntity<Board> createBoard(@Valid @RequestBody
BoardRequestDTO boardRequestDTO) {
Board board = new Board();
board.setName(boardRequestDTO.getName());
board.setCompanyId(Integer.valueOf(boardRequestDTO.getCompanyId()));
board.setCode(boardRequestDTO.getCode());
Board dbBoard = boardRepository.save(board);
return new ResponseEntity<>(dbBoard, HttpStatus.CREATED);
}
并具有以下处理验证错误的异常处理程序
@ControllerAdvice
public class ExceptionHandlerConfig extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object>
handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
ValidationErrorResponses validationErrorResponses = new
ValidationErrorResponses();
for (FieldError fieldError : ex.getBindingResult().getFieldErrors())
validationErrorResponses.addError(new ValidationError(fieldError.getField(),fieldError.getDefaultMessage()));
ResponseEntity<Object> responseEntity = new ResponseEntity<Object>
(validationErrorResponses, HttpStatus.UNPROCESSABLE_ENTITY);
return responseEntity;
}
}
当我通过邮递员发送失败请求时,得到的响应是可以预期的:
{
"errors": [
{
"field": "companyId",
"message": "Must be digit"
}
]
}
但是当我尝试对此端点实施以下单元测试时,我得到了org.springframework.web.client.HttpClientErrorException $ UnprocessableEntity:422 null
:
boardDTO.setCompanyId("");
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");
headers.set("Accept", "application/json");
HttpEntity<ValidationErrorResponses> httpEntity = new HttpEntity(boardDTO, headers);
ResponseEntity<ValidationErrorResponses> responseEntity =
restTemplate.postForEntity(url, httpEntity, ValidationErrorResponses.class);
ValidationErrorResponses responseBody = responseEntity.getBody();
assertEquals(422, responseEntity.getStatusCode());
assertEquals("companyId", responseBody.getErrors().get(0).getField());
assertEquals("Must be digit", responseBody.getErrors().get(0).getMessage());
我应该怎么做才能使测试正常工作?
答案 0 :(得分:0)
为避免测试实现,我建议针对“已引发”异常进行测试。异常的返回消息应该是该异常的单元测试的一部分:
@Test(expected = MethodArgumentNotValidException.class)
public void testMethodArgumentNotValidException() {
boardDTO.setCompanyId("");
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");
headers.set("Accept", "application/json");
HttpEntity<ValidationErrorResponses> httpEntity = new HttpEntity(boardDTO, headers);
ResponseEntity<ValidationErrorResponses> responseEntity =
restTemplate.postForEntity(url, httpEntity, ValidationErrorResponses.class);
}
否则问自己,是否可以通过用户接受测试来处理结果正文?
答案 1 :(得分:0)
restTemplate.postForEntity将在状态为> = 400和<500时抛出HttpClientErrorException。在此处编写测试的一种简单方法是:
try {
restTemplate.postForEntity(url, httpEntity, ValidationErrorResponses.class);
fail("should throw exception");
} catch (HttpClientErrorException e) {
// Asserts go here using `e`
}