我的控制器(Spring 4.1)中有以下图像下载方法:
@RequestMapping(value = "/get/image/{id}/{fileName}", method=RequestMethod.GET)
public @ResponseBody byte[] showImageOnId(@PathVariable("id") String id, @PathVariable("fileName") String fileName) {
setContentType(fileName); //sets contenttype based on extention of file
return getImage(id, fileName);
}
Run Code Online (Sandbox Code Playgroud)
以下ControllerAdvice方法应处理不存在的文件并返回json错误响应:
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public @ResponseBody Map<String, String> handleResourceNotFoundException(ResourceNotFoundException e) {
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put("error", e.getMessage());
return errorMap;
}
Run Code Online (Sandbox Code Playgroud)
我的JUnit测试完美无瑕
(编辑这是因为扩展.bla:这也适用于appserver):
@Test
public void testResourceNotFound() throws Exception {
String fileName = "bla.bla";
mvc.perform(MockMvcRequestBuilders.get("/get/image/bla/" + fileName)
.with(httpBasic("test", "test")))
.andDo(print())
.andExpect(jsonPath("$error").value(Matchers.startsWith("Resource not found")))
.andExpect(status().is(404));
}
Run Code Online (Sandbox Code Playgroud)
并给出以下输出:
MockHttpServletResponse: …Run Code Online (Sandbox Code Playgroud)