2016-04-11 34 views
1

我一直在围绕试图修复一个测试,并且没有任何东西或其他在线来源提供了解决方案。我有此@ControllerAdvice方法来处理MyException例外是:@ExceptionHandler未被调用测试

@ControllerAdvice 
public class MyControllerAdvice { 
    @ExceptionHandler(MyException.class) 
    @ResponseBody 
    public HttpEntity<ErrorDetail> handleMyException(MyException exception) { 
     return new ResponseEntity<>(exception.getErrorDetail(), exception.getHttpStatus(); 
    } 
} 

和我有一个控制器:

@Controller 
@RequestMapping(value = "/image") 
public class ImageController { 
    @Autowired 
    private MyImageService imageService; 

    @RequestMapping(value = "/{IMG_ID}", method = RequestMethod.GET, 
     produces = MediaType.IMAGE_PNG_VALUE) 
    public HttpEntity<?> getImage(String imageId) { 
     byte[] imageBytes = imageService.findOne(imageId); // Exception thrown here 
     .... 
     return new ResponseEntity<>(imageBytes, HttpStatus.OK); 
    } 
    ... 
} 

其是通过测试:

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration(classes = MyApplication.class) 
@WebAppConfiguration 
@IntegrationTest("server.port:0") 
public class ThumbnailControllerTest { 
    @Autowired 
    private ImageController testObject; 
    private ImageService mockImageService = mock(ImageService.class); 

    @Autowired 
    protected WebApplicationContext webApplicationContext; 
    private MockMvc mockMvc; 

    @Before 
    public void setup() { 
     testObject.setImageService(mockImageService); 
     mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); 
    } 

    @Test 
    public void testImageWhichDoesntExistReturns404() { 
      doThrow(new MyException("Doesn't exist", HttpStatus.NOT_FOUND)) 
       .when(mockImageService).findOne(anyString()); 

      mockMvc.perform(get("/image/doesnt_exist")) 
       .andExpect(status().isNotFound()); 
    } 
} 

我有一个类似的设置对于其他测试,但这些似乎通过。然而,对于这个我得到:Failed to invoke @ExceptionHandler method: public org.springframework.http.HttpEntity<mypackage.ErrorDetail>但是我知道它被调用,因为当我通过它时被调用,并且日志显示它已被检测到(Detected @ExceptionHandler methods in MyControllerAdvice)。

我的想法是,这是因为HttpMessageConverters未正确解析并尝试使用ModelAndView方法解析输出,而不是所需的JSON格式。我无法强制执行此操作,通过将standaloneSetup用于MockMvc(使用ControllerAdvice和HttpMessageConverters进行配置)或使用所需类型的HttpMessageConverters bean强制执行此操作。

我使用Spring的依赖:

org.springframework.boot:spring-boot-starter-web:jar:1.3.1.RELEASE 
org.springframework.boot:spring-boot-starter:jar:1.3.1.RELEASE 
org.springframework.boot:spring-boot-starter-test:jar:1.3.1.RELEASE 
org.springframework.boot:spring-boot-starter-data-rest:jar:1.3.1.RELEASE 

我在做什么错?

回答

1

我已经能够跟踪到produces = MediaType.IMAGE_PNG_VALUE。如果你删除它,它可以正常工作(假设你的ErrorDetail是JSON序列化的)。事情是,AbstractMessageConverterMethodProcessor坚持要求的类型。它只是跳过JSON转换器,因为它不能生成图像/ PNG。指定produces = {MediaType.IMAGE_PNG_VALUE, MediaType.APPLICATION_JSON_VALUE}也没有帮助:它只是挑选第一个类型并坚持使用它。我不知道如何使它与produces一起工作。欢迎任何改进或更正。

+0

感谢帮助了很多,我已经指定内容类型作为响应的标题,而不是生成问题已经解决了。 – joelc

相关问题