此问题基于this question。
通过提供的评论,我编写了三种不同的测试来验证正确设置的内容类型。
@Test
public void testGetImageJpg_ShouldSucceed() throws Exception {
File testImage = new File(TestConstants.TEST_IMAGE_JPG);
byte[] expectedBytes = IOUtils.toByteArray(new FileInputStream(testImage));
when(service.getImage(anyString(), anyString())).thenReturn(testImage);
mockMvc.perform(get("/getImage/id/bla.jpg").sessionAttrs(session))
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.IMAGE_JPEG))
.andExpect(content().bytes(expectedBytes));
}
@Test
public void testGetImagePng_ShouldSucceed() throws Exception {
File testImage = new File(TestConstants.TEST_IMAGE_PNG);
byte[] expectedBytes = IOUtils.toByteArray(new FileInputStream(testImage));
when(service.getImage(anyString(), anyString())).thenReturn(testImage);
mockMvc.perform(get("/getImage/id/bla.png").sessionAttrs(session))
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.IMAGE_PNG))
.andExpect(content().bytes(expectedBytes));
}
@Test
public void testGetImageGif_ShouldSucceed() throws Exception {
File testImage = new File(TestConstants.TEST_IMAGE_GIF);
byte[] expectedBytes = IOUtils.toByteArray(new FileInputStream(testImage));
when(service.getImage(anyString(), anyString())).thenReturn(testImage);
mockMvc.perform(get("/getImage/id/bla.gif").sessionAttrs(session))
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.IMAGE_GIF))
.andExpect(content().bytes(expectedBytes));
}
这是我的控制器,所有测试都成功:
@RequestMapping(value="/getImage/{id}/{path}", produces = {"image/png","image/jpeg","image/gif"})
@ResponseBody
byte[] getImage(@PathVariable("id") String id,
@PathVariable("path") String path) throws ImageNotFoundException {
File imageFile = service.getImage(id, path);
InputStream in;
try {
in = new FileInputStream(imageFile);
return IOUtils.toByteArray(in);
} catch (IOException e) {
throw new ImageNotFoundException();
}
}
但是当我将生产值的顺序更改为
时 produces = {"image/jpeg","image/png","image/gif"}
png的测试失败了:
java.lang.AssertionError: Content type expected:<image/png> but was:<image/jpeg>
我很困惑,改变产品价值的顺序会导致不同的结果。
有没有人观察到这一点,这是一个错误还是我错过了什么?