尝试测试HTTP POST的处理时HttpMediaTypeNotSupportedException [英] HttpMediaTypeNotSupportedException when trying to test handling of HTTP POST
问题描述
我正在尝试在spring框架中测试 POST
方法但我一直都会遇到错误。
I am trying to test POST
method in spring framework but I keep getting errors all the time.
我首先尝试了这个测试:
I first tried this test:
this.mockMvc.perform(post("/rest/tests").
param("id", "10").
param("width","25")
)
.andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk());
并收到以下错误:
org.springframework.http.converter.HttpMessageNotReadableException
然后我尝试修改测试如下:
Then I tried to modify the test as below:
this.mockMvc.perform(post("/rest/tests/").
content("{\"id\":10,\"width\":1000}"))
.andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk());
但是出现以下错误:
org。 springframework.web.HttpMediaTypeNotSupportedException
我的控制器是:
@Controller
@RequestMapping("/rest/tests")
public class TestController {
@Autowired
private ITestService testService;
@RequestMapping(value="", method=RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void add(@RequestBody Test test)
{
testService.save(test);
}
}
其中测试
class有两个字段成员: id
和 width
。简而言之,我无法为控制器设置参数。
Where Test
class has two field members: id
and width
. In a few word I am unable to set the parameters for the controller.
设置参数的正确方法是什么?
What's the proper way to set the parameters?
推荐答案
您应该在帖子请求中添加内容类型 MediaType.APPLICATION_JSON
,例如
You should add a content type MediaType.APPLICATION_JSON
to the post request, e.g.
this.mockMvc.perform(post("/rest/tests/")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"id\":10,\"width\":1000}"))
.andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk());
这篇关于尝试测试HTTP POST的处理时HttpMediaTypeNotSupportedException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!