gpt4 book ai didi

java - 如何从 JUNIT 测试用例中使用 @RequestBody 调用 Spring Controller 的方法

转载 作者:行者123 更新时间:2023-12-01 21:27:39 31 4
gpt4 key购买 nike

我有一种 Controller 方法。

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public String uploadFiles(@RequestBody MyModel myModel) {...}

我必须从 JUNIT 测试用例中调用它。

到目前为止,我尝试了不同的方法,其中一些方法如下,它给了我

java.lang.AssertionError: Status expected:<200> but was:<415>

MvcResult result;   
result = getMockMvc().perform(post("/fileUpload"))
.andExpect(status().isOk())
.andReturn();

result = getMockMvc().perform(post("/fileUpload").accept(APPLICATION_JSON_CHARSET_UTF_8))
.andExpect(status().isOk())
.andReturn();

我无法在 RequestHeader、RequestParam 或 PathVariable 中传递我的参数。

最佳答案

你可以试试这个:

MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(url).contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON).content(jsonContent)).andReturn();

其中 url = "/fileUpload"和 jsonContent 是您请求的 String 类型的 json 内容。

关于java - 如何从 JUNIT 测试用例中使用 @RequestBody 调用 Spring Controller 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37827893/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com