我一直在围绕试图修复一个测试,并且没有任何东西或其他在线来源提供了解决方案。我有此@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
我在做什么错?
感谢帮助了很多,我已经指定内容类型作为响应的标题,而不是生成问题已经解决了。 – joelc