我在一个类中设置了一个简单的 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() 行上显示消息“Status Expect:<200> but was:<415>”。在控制台中,我可以看到以下消息:
解决处理程序 [null] 的异常:org.springframework.web.HttpMediaTypeNotSupportedException:不支持内容类型“null”
415 是“内容不受支持”错误。
Spring 版本 4.1.7。
对于我做错了什么有什么建议吗?提前致谢。
最佳答案
已修复。执行 POST 时缺少内容类型。我将其添加到测试中并且成功运行:
.header("Content-Type", MediaType.TEXT_PLAIN_VALUE)
关于java - 简单的 Spring REST 测试抛出 HttpMediaTypeNotSupportedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33602060/