按照此处Spring Boot Remove Whitelabel Error Page的建议,我创建了一个自定义错误控制器,以json格式返回自定义错误响应,看起来像
@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错误响应。
现在我正在尝试编写一个Test,以测试是否有一个不存在的enpoint,CustomErrorController处理它并返回一个带有json响应的404,如:
{
"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
无法找到CustomErrorController
。答案 0 :(得分:1)
您可以使用TestRestTemplate
进一步改进。这样您不仅可以进行适当的URI调用,还可以让您将响应序列化到它回来的实际对象中,以验证您的身体和其他元素是否实际存在。
简要示例:
// Elsewhere...
@Autowired
private TestRestTemplate template;
// In your tests...
ErrorJson result = template.getForObject("/error", ErrorJson.class);
// Inspect the result!