Если я правильно понимаю вашу проблему, вы можете использовать @RunWith
с SpringRunner
и @WebMvcTest
с вашим контроллером и классами обработчика исключений .
Поскольку ваш вопрос не показывает, как выглядит ваш контроллер, давайте рассмотрим следующий контроллер, который возвращает приветствие для данного имени:
@Data
public class Greeting {
private String content;
}
@Validated
@RestController
public class GreetingController {
@GetMapping(path = "/greeting", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Greeting> getGreeting(
@RequestParam @Size(min = 2, max = 10) String name) {
Greeting greeting = new Greeting();
greeting.setContent("Hello " + name + "!");
return ResponseEntity.ok(greeting);
}
}
Теперь давайте рассмотрим обработчик исключений для ConstraintViolationException
, который будет сгенерирован при сбое проверки:
@Data
public class ApiError {
private String message;
private HttpStatus status;
private Object details;
}
@Data
public class InvalidValue {
private String name;
private Object value;
private String message;
}
@ControllerAdvice
public class WebApiExceptionHandler {
@ExceptionHandler({ConstraintViolationException.class})
public ResponseEntity<Object> handleConstraintViolation(ConstraintViolationException ex,
WebRequest request) {
List<InvalidValue> invalidValues = ex.getConstraintViolations()
.stream()
.map(this::toInvalidValue)
.collect(toList());
ApiError apiError = new ApiError();
apiError.setMessage("Validation error");
apiError.setStatus(HttpStatus.BAD_REQUEST);
apiError.setDetails(invalidValues);
return new ResponseEntity<>(apiError, new HttpHeaders(), apiError.getStatus());
}
private InvalidValue toInvalidValue(ConstraintViolation violation) {
InvalidValue invalidValue = new InvalidValue();
invalidValue.setName(violation.getPropertyPath().toString());
invalidValue.setValue(violation.getInvalidValue());
invalidValue.setMessage(violation.getMessage());
return invalidValue;
}
}
С этим вы можете написать тесты и ожидания, как показано ниже:
@RunWith(SpringRunner.class)
@WebMvcTest({GreetingController.class, WebApiExceptionHandler.class})
public class GreetingControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
@SneakyThrows
public void getGreeting_shouldReturn200_whenNameIsValid() {
mockMvc.perform(
get("/greeting")
.param("name", "foo")
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.*", hasSize(1)))
.andExpect(jsonPath("$.content").value("Hello foo!"));
}
@Test
@SneakyThrows
public void getGreeting_shouldReturn400_whenNameIsInvalid() {
mockMvc.perform(get("/greeting").param("name", "_"))
.andDo(print())
.andExpect(status().isBadRequest())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.*", hasSize(3)))
.andExpect(jsonPath("$.message").value("Validation error"))
.andExpect(jsonPath("$.status").value("BAD_REQUEST"))
.andExpect(jsonPath("$.details", hasSize(1)))
.andExpect(jsonPath("$.details[0].*", hasSize(3)))
.andExpect(jsonPath("$.details[0].name", is("getGreeting.name")))
.andExpect(jsonPath("$.details[0].value", is("_")))
.andExpect(jsonPath("$.details[0].message", is("size must be between 2 and 10")));
}
}