简单的Spring REST测试抛出HttpMediaTypeNotSupportedException



我在一个类中设置了一个简单的Spring REST方法,该方法应该只返回POST请求中发送给它的文本作为响应。MyService.java类中的我的方法:

@RequestMapping(value = "/my/url", method = RequestMethod.POST, consumes = MediaType.TEXT_PLAIN_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> myMethod(@RequestBody final String body) {
    return new ResponseEntity<String>(body, HttpStatus.OK);
}

我有一个单元测试,它使用Spring的MockMvc来测试方法:

@Autowired
private MyService service;
private MockMvc mockMvc;
@Before
public void setup() throws Exception {
    mockMvc = standaloneSetup(service).build();
}
@Test
public void myTest() throws Exception {
    Assert.assertNotNull(service); // Class has been instantiated
    final String content = "Hello world";
    final String url = "/my/url";
    final MvcResult result = mockMvc.perform(post(url) //
            .content(content) //
            .accept(MediaType.TEXT_PLAIN_VALUE)) //
            .andExpect(status().isOk()) //
            .andReturn();
}

测试失败,单元测试的perform()行上显示消息"预期状态:<200>但实际为:<415>"。在控制台中,我可以看到以下消息:

正在解析来自处理程序[null]的异常:org.springframework.web.HttpMediaTypeNotSupportedException:不支持内容类型"null"的

415是"不支持内容"错误。

春季版本4.1.7。

关于我做错了什么,有什么建议吗?提前谢谢。

已修复。执行POST时缺少内容类型。我把这个添加到测试中,它成功地工作了:

.header("Content-Type", MediaType.TEXT_PLAIN_VALUE)

相关内容

  • 没有找到相关文章

最新更新