如何在RequestMapping Annotation中测试具有多个值的Spring控制器?

时间:2016-09-08 10:57:27

标签: java spring testing content-type

我想测试某种控制器方法,即向客户端提供图像。 这些图像具有不同的内容类型(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();
    }
}

我如何编写涵盖任何内容类型的测试: 我目前的测试:

@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));

}

如何使用andExpect(..)涵盖多种内容类型? 理想情况下,它应该测试内容类型是jpg还是png或gif。

0 个答案:

没有答案