java - 完成 406 NOT_ACCEPTABLE - 在 SpringBoot 中测试 WebLayer
问题描述
我在 Spring Boot v2.1.0.RELEASE 应用程序中有这个方法。
@GetMapping(value = "/wildProject", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<WildProject>> getList(HttpServletRequest request,
HttpServletResponse response)
throws Exception {
List<WildProject> list = authorisationService.getList();
System.out.println("-----------------");
System.out.println(list);
System.out.println("-----------------");
return ok().body(list);
}
这个测试:
this.mockMvc.perform(get("/wildProject")
//.accept(MediaType.APPLICATION_JSON_UTF8_VALUE))
// .andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk());
这是测试的结果:
20:03:38.253 [main] DEBUG o.s.w.s.m.m.a.HttpEntityMethodProcessor - Using 'application/json', given [*/*] and supported [application/json]
20:03:38.255 [main] WARN o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
20:03:38.256 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Completed 406 NOT_ACCEPTABLE
MockHttpServletRequest:
HTTP Method = GET
Request URI = /wildProject
Parameters = {}
Headers = {Content-Type=[application/json;charset=UTF-8]}
Body = null
Session Attrs = {}
Handler:
Type = com.bonansa.controller.AuthorisationController
Method = public org.springframework.http.ResponseEntity<java.util.List<com.bonansa.WildProject>> com.bonansa.controller.AuthorisationController.getList() throws java.lang.Exception
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.HttpMediaTypeNotAcceptableException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 406
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
和
@JsonSerialize(as = IWildProject.class)
public interface IWildProject {
..
}
解决方案
您不需要Content-Type
为GET
请求设置标头,因为您没有发送任何内容而是请求某些内容。在这种Accept
情况下,标题是要寻找的。
而且,MediaType.APPLICATION_JSON_VALUE
不会匹配MediaType.APPLICATION_JSON_UTF8_VALUE
。
我建议将那段代码重构为:
this.mockMvc.perform(get("/wildProject")
.accept(MediaType.APPLICATION_JSON_VALUE))
// .andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk());
推荐阅读
- python - numpy.ndarray 对象没有属性 imshow
- java - 即使我在我的适配器类中初始化它,我可以从不同的 Activity / Fragment 暂停/停止 ExoPlayer 吗?
- azure - Azure Speech to Text:自定义语音模型 - 相关文本“继续”
- javascript - react-native:如何阻止标签重新渲染?
- sql - 如何将一个查询结果显示为 2 行?
- java - 设置了 java.security.AllPermission 时仍然抛出 Java 安全异常
- python - 在 Python 中搜索字典
- ios - Flutter - 尝试在 iOS 上构建时出错:错误:类型 'Profile' 没有成员 'PictureMode'
- batch-file - 如何仅将 ftype 路径输出到 .txt
- spring - 在 Kotlin 和 JUnit5 中测试 Spring Boot 缓存