jeudi 8 septembre 2016

Is produces of @RequestMapping sensitive to order of values ?

This question is based on this question.

With provided comments, i had written three different tests to validate properly set content-types.

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

}

This is my controller, where all tests succeed:

@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 = handler.getImage(id, path);
    InputStream in;        
    try {
        in = new FileInputStream(imageFile);
        return IOUtils.toByteArray(in);
    } catch (IOException e) {           
        throw new ImageNotFoundException();
    }
}

But when I change the order of produces value to

produces = {"image/jpeg","image/png","image/gif"}

The test for png is failing:

java.lang.AssertionError: Content type expected:<image/png> but was:<image/jpeg>

Im little confused, that changing the order of produces values leads to different results.

Does anyone observed this, is it a bug or did I miss something ?

Aucun commentaire:

Enregistrer un commentaire