尝试测试我的RestControllerAdviser,它使用的是@ControllerAdvice
批注,并且其中有一些ExceptionHandlers
,例如。
@ExceptionHandler(value = InvocationTargetException.class)
public ResponseEntity<Object> handleInvocationTargetException(InvocationTargetException e) {
String errorMessage = "Error Caught: Internal Server Error - Invocation Target Exception.";
log.error(errorMessage, e);
return response(errorMessage, HttpStatus.INTERNAL_SERVER_ERROR);
}
...
/**
* No handler found, for things such as 404 errors.
*
* @param e
* @return
*/
@Override
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException e, HttpHeaders headers,
HttpStatus status, WebRequest request) {
String errorMessage = "Error Caught: " + e.getMessage();
log.error(errorMessage, e);
return response(errorMessage, status);
}
到目前为止,我尝试设置我的测试时,我遇到了其他一些StackOverflow问题,以使用MockMvc并获取MvcResult对象。我可以很好地检查状态...但是结果的内容不是我期望的为空。
例如,我的测试文件是...
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { RestControllerAdviserTestConfig.class })
public class RestControllerAdviserTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test(expected = NoHandlerFoundException.class)
public void noHandlerFoundExceptionTest() throws Exception {
MvcResult result = mockMvc.perform(get("/invalidurl")).andExpect(status().isNotFound()).andReturn();
}
}
最后一次测试结果对象时,在调试器中查找内容时没有内容...当我希望基于我的ExceptionHandler时,它会带有类似“ Error Caught:..”的内容。
如何测试对异常处理程序的响应内容?