听从这里的建议
Spring Boot Remove Whitelabel Error Page
@RestController
public class CustomErrorController implements ErrorController {
private static final String PATH = "/error";
@Value("${spring.debug:false}")
private boolean debug;
@Autowired
private ErrorAttributes errorAttributes;
@RequestMapping(value = PATH)
ErrorJson error(HttpServletRequest request, HttpServletResponse response) {
return new ErrorJson(response.getStatus(), getErrorAttributes(request, debug));
}
private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace);
}
@Override
public String getErrorPath() {
return PATH;
}
}
哪里
CustomErrorController
ErrorController
和
ErrorJson
只是一个格式化json错误响应的简单类。
{
"status": 404,
"error": "Not Found",
"message": "No message available",
"timeStamp": "Thu Jun 29 14:55:44 PDT 2017",
"trace": null
}
我的测试目前看起来像
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class CustomErrorControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void invalidURLGet() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/foo"))
.andExpect(status().is(404))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andReturn();
}
}
我得到状态为的错误响应
404
MockHttpServletResponse
作为:
MockHttpServletResponse:
Status = 404
Error message = null
Headers = {X-Application-Context=[application:development:-1]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
-
为什么内容正文为空。是
MockMvc
自定义错误控制器
-
我是否错误地测试了错误行为。如果是这样,我如何测试自定义错误响应?