【发布时间】:2017-12-08 20:32:32
【问题描述】:
我正在使用 Spring 4.3.8.RELEASE。我想为特定的 Forbidden 错误设置错误消息。我的控制器中有这个。 “响应”的类型为“javax.servlet.HttpServletResponse”。
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentLength(errorMsg.length());
byte[] buffer = new byte[10240];
final OutputStream output = response.getOutputStream();
output.write(buffer, 0, errorMsg.length());
output.flush();
但是,内容似乎没有被返回,至少我在单元测试中看不到它......
final MvcResult result = mockMvc.perform(get(contextPath + "/myurl")
.contextPath(contextPath)
.principal(auth)
.param("param1", param1)
.param("param2", param2))
.andExpect(status().isForbidden())
.andReturn();
// Verify the error message is correct
final String msgKey = "error.code";
final String errorMsg = MessageFormat.format(resourceBundle.getString(msgKey), new Object[] {});
Assert.assertEquals("Failed to return proper error message.", errorMsg, result.getResponse().getContentAsString());
断言失败,表示响应字符串为空。将响应写回 HttpServletResponse 缓冲区的正确方法是什么?
【问题讨论】:
标签: spring servlets junit httpresponse mockmvc