我一直在兜圈子试图修复一个测试,但 SO 或其他在线资源上没有提供解决方案。我有这种@ControllerAdvice
方法来处理MyException
异常,即:
@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 来强制执行此操作。
我正在使用弹簧依赖项:
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
我究竟做错了什么?