我有@ControllerAdvice
个带注释的类,它正在处理BadRequestException extends RuntimeException
异常。
现在假设我有端点:
@PostMapping(value = "/createAccount")
public ResponseEntity<CreateAccountResponse> createAccount(@RequestBody @Valid CreateAccountRequest createAccountRequest) {...}
万一发生意外情况,端点抛出BadRequestException
(HTTP状态为400),该错误构造了如下的JSON对象:
{
"errorCode": 123,
"errorMessage: "Failure reason"
}
有什么方法可以使用Spring REST Docs记录这种情况?
这是我的方法的示例:
@Test
public void createAccountFailExample() {
RestDocumentationResultHandler docs = document("create-acc-fail-example",
responseFields(
fieldWithPath("errorCode").type("Integer").description("Error code"),
fieldWithPath("errorMessage").type("String").description("Error message")
)
);
org.assertj.core.api.Assertions.assertThatThrownBy(() -> this.mockMvc.perform(RestDocumentationRequestBuilders.post("/createAccount")
.contextPath("/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(new CreateAccountRequest("nameTest", "surnameTest"))))
.andExpect(status().isBadRequest())
.andDo(docs)).hasCause(new BadRequestException(ServiceError.SOME_FAIL_REASON));
}
在这种情况下,测试通过了,但是没有创建任何文档(.adoc)文件。
当我尝试这样的事情时:
ResultActions resultActions = this.mockMvc.perform(RestDocumentationRequestBuilders.post("/createAccount")
.contextPath("/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(new CreateAccountRequest("testName", "testSurname"))))
.andExpect(status().isBadRequest())
.andDo(docs);
测试失败,因为NestedServletException
引发了BadRequestException
,并且没有创建任何文档。