如何使用mockito为下面的异常处理方法编写单元测试?

Man*_*gii 0 rest junit mockito java-8 spring-boot

@ExceptionHandler({ ConstraintViolationException.class })
public ResponseEntity<Object> handleConstraintViolation(ConstraintViolationException ex, WebRequest request) {
    StringBuilder messageBuilder = new StringBuilder("Validation failed for: ");
    ex.getConstraintViolations()
        .stream()
        .forEach(v -> messageBuilder
            .append("property: [" + v.getPropertyPath() + "], value: [" + v.getInvalidValue() + "], constraint: [" + v.getMessage() + "]"));
    return new ResponseEntity<>(responseBuilder
        .createErrorResponse(INVALID_PARAMETER,
            messageBuilder.toString()), getHeaders(), BAD_REQUEST);
}
Run Code Online (Sandbox Code Playgroud)

我想测试这个@ControllerAdvice方法

Nic*_*tti 5

如果您只想测试该方法,只需创建(您的输入)的实例并检查应用于该方法ConstraintViolationException的输出即可。handleConstraintViolation你可以这样做:

ConstraintViolationException exception = mock(ConstraintViolationException.class);
WebRequest webRequest = mock(WebRequest.class); 
YourControllerAdvice controllerAdvice = new YourControllerAdvice();
Set<ConstraintViolation<?>> violations = new HashSet<>();
ConstraintViolation mockedViolation = mock(ConstraintViolation.class);
given(mockedViolation.getPropertyPath()).willReturn("something");
// mock answer to other properties of mockedViolations 
...
violations.add(mockedViolation);  
given(exception.getContraintViolations()).willReturn(violations);

ResponseEntity<Object> response = controllerAdvice.handleContraintViolation(exception, webRequest);

assertThat(response.getStatusCode(), is(HttpStatus.BAD_REQUEST));
Run Code Online (Sandbox Code Playgroud)

加上响应主体上的其他断言。然而,很难知道ConstraintViolationExceptionspring 抛出的所有不同实例是什么样子。

相反,我建议您查看 MockMvc,它是spring-boot-starter-test. 通过这种方式,您可以测试异常处理程序是否按预期使用,并且可以验证两者ResponseEntity是否违反约束。

@WebMvcTest(YourController.class)
public class YourControllerMvcTest {

  @Autowired
  private MockMvc mvc;

  @Test
  public void constraintViolationReturnsBadRequest() throws Exception {
    // Instantiate the DTO that YourController takes in the POST request
    // with an appropriate contraint violation
    InputDto invalidInputDto = new InputDto("bad data");
    MvcResult result = mvc.perform(post("/yourcontrollerurl")
            .content(invalidInputDto)
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isBadRequest());

    // assert that the error message is as expected
    assertThat(result.getResponse().getContentAsString(), containsString("default message [must match"));
  } 
}
Run Code Online (Sandbox Code Playgroud)

MockMvc 也有很好的 json 支持,因此可以添加:

.andExpect(MockMvcResultMatchers.jsonPath("$.field").value("expected value"))
Run Code Online (Sandbox Code Playgroud)

而不是将响应验证为字符串。