我已经创建了一个Spring Boot应用程序,并且正在使用MockMvc来测试该应用程序。我的应用程序有一个拦截器,用于记录状态代码和响应内容的长度。我在运行Springboot应用程序与使用模拟MVC测试它时在行为上存在差异。
应用代码:
@RestController
@EnableAutoConfiguration
public class DemoApp{
public static void main(String[] args) {
SpringApplication.run(DemoApp.class, args);
}
@RequestMapping(value = "/hello")
public String hello() {
return "Hello World";
}
@RequestMapping(value = "/exception")
public String exception() throws FileNotFoundException {
throw new FileNotFoundException();
}
拦截器代码:
@Component
public class MyInterceptor implements HandlerInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(MyInterceptor.class);
public MyInterceptor() {
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception exception) throws Exception {
LOGGER.info("Status Code:"+String.valueOf(response.getStatus()));
LOGGER.info("Transfer Encoding:"+response.getHeader(HeaderConstants.TRANSFER_ENCODING));
LOGGER.info("Content Length:"+response.getHeader(HeaderConstants.CONTENT_LENGTH));
}
}
测试用例:
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders.standaloneSetup(DemoApp.class).addInterceptors(MyInterceptor).build();
}
@SuppressWarnings("deprecation")
@Test
public void testException() throws Exception {
try {
mvc.perform(get("/exception").accept(MediaType.TEXT_PLAIN)).andExpect(status().is5xxServerError()).andDo(print());
Assert.fail("Exception expected from server");
} catch (Exception e) {
/* NOOP */
}
}
应用程序返回分块的状态代码500和Transfer-Encoding
,而测试用例返回状态代码200,并且Transfer-Encoding
API缺少/exception
标头。
有人可以让我知道这是预期的行为还是我做错了什么?