java - 简单的 Spring REST 测试抛出 HttpMediaTypeNotSupportedException

标签 java spring rest

我在一个类中设置了一个简单的 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/

相关文章:

java - 如何从 oracle 触发器中调用 java 类?

java - 在初始化 SpringBootApplication 的 ApplicationContextInitializer bean 之前启动一个 @WebServlet

java - 消息新对象和使用静态方法的测试方法

java - Thymeleaf 错误加载静态文件

java jersey 2如何使用post处理常规html表单数组?

java - 为什么我的 fragment 没有取代我的 Activity 布局?

java - HttpURLConnection RequestPropertys 为空

java - 从属性文件中删除键和值?

java - 为什么我在启动 springdata Rest api 时遇到异常

java - 使用 REST API 下载文件