Java MockMVC为对象列表返回406(对于一个对象测试工作),为什么?
在SpringBoot应用程序(springBootVersion='2.1.1.RELEASE')中,我有两个ReST端点。一个返回对象,第二个返回对象列表。我尝试使用编写此端点的测试 测试单个对象,按预期工作。对对象列表的测试返回的是Java MockMVC为对象列表返回406(对于一个对象测试工作),为什么?,java,spring,spring-boot,Java,Spring,Spring Boot,在SpringBoot应用程序(springBootVersion='2.1.1.RELEASE')中,我有两个ReST端点。一个返回对象,第二个返回对象列表。我尝试使用编写此端点的测试 测试单个对象,按预期工作。对对象列表的测试返回的是406,而不是200。下面是我的代码,控制器+测试。 单对象静止: @ResponseBody @RequestMapping(value = {"/example", "/example.html"}) public R
406
,而不是200
。下面是我的代码,控制器+测试。
单对象静止:
@ResponseBody
@RequestMapping(value = {"/example", "/example.html"})
public ResponseEntity<SampleObject> example() {
SampleObject sampleObj = generateSampleObject();
return new ResponseEntity<>(sampleObj, HttpStatus.OK);
}
列表的ReST端点:
@ResponseBody
@RequestMapping(value = {"/", "/index.html"})
public ResponseEntity<List<SampleObject>> all() {
List<SampleObject> sampleObjectList = generateListOfSampleObject();
return new ResponseEntity<>(sampleObjectList, HttpStatus.OK);
}
有什么区别?为什么对一个对象测试有效,但对列表无效
添加:
当我启动应用程序时,浏览器中的所有程序都工作正常,两个端点都正常。让我们检查代码:
显示您的后端没有返回客户端请求的响应HTTP 406
- 您的客户端(您的测试)请求
应用程序\u JSON\u UTF8\u值
表示内容类型为APPLICATION\u JSON\u UTF8\u VALUE
,并采用JSON
字符编码UTF-8
一个可能的原因可能是在您的列表响应中,您有一些未在UTF-8中编码的对象,请注意,
MediaType。应用程序\u JSON\u UTF8
的存在是有原因的。请打开org.springframework.web
的日志,调试并发布结果;此外,您应该在测试控制台上从MockMvc获得一份报告。在测试类的开头使用@RunWith(SpringRunner.class)
运行测试。
@ResponseBody
@RequestMapping(value = {"/", "/index.html"})
public ResponseEntity<List<SampleObject>> all() {
List<SampleObject> sampleObjectList = generateListOfSampleObject();
return new ResponseEntity<>(sampleObjectList, HttpStatus.OK);
}
@Test
public void shouldCheckHomePage() throws Exception {
MvcResult mvcResult = this.mockMvc.perform(get("/")
.accept(MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE)))
.andExpect(status().isOk()).andReturn();
}