How to test Spring controller with multiple values for produces in RequestMapping Annotation?

混江龙づ霸主 提交于 2019-12-25 09:09:15

问题


I wanna test a certain controller method, which is serving images to client. Those images have different content types (jpg, png, gif).

@RequestMapping(value="/getImage/{id}/{path}", produces = {"image/jpg", "image/gif", "image/png"})
@ResponseBody
byte[] getImage(@PathVariable("id") String id,
        @PathVariable("path") String path)  {      
    File imageFile = handler.getImage(id, path);
    InputStream in;        
    try {
        in = new FileInputStream(imageFile);
        return IOUtils.toByteArray(in);
    } catch (IOException e) {           
        e.printStackTrace();
    }
}

How would I write a test, which covers any content type: my current test:

@Test
public void testGetImage_shouldSucceed() throws Exception {
    File testImage = new File(TestConstants.TEST_IMAGE);
    byte[] expectedBytes = IOUtils.toByteArray(new FileInputStream(testImage));
    when(service.getImage(anyString(), anyString())).thenReturn(testImage);
    mockMvc.perform(get("/getImage/{id}/{path}", "1L", "bla").sessionAttrs(session))
            .andExpect(status().isOk()).andExpect(content().contentType(MediaType.IMAGE_JPEG))
            .andExpect(content().bytes(expectedBytes));

}

How can I use andExpect(..) to cover multiple content-types ? Ideally it should test if the content type is jpg OR png OR gif.

来源:https://stackoverflow.com/questions/39389144/how-to-test-spring-controller-with-multiple-values-for-produces-in-requestmappin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!