我不能通过在mockMvc中使用spring-test来测试控制器。我想知道用@RequestPart测试API的正确方法。
测试的方法是这样。
@RequestMapping(value = "/", method = RequestMethod.POST)
public ResponseEntity<Object> replaceFile(
@RequestPart("files") Map<String, Object> files,
@RequestPart("fileKey") String fileKey)为了进行测试,我构建了一个模拟请求,如下所示。
MockMultipartFile blob = new MockMultipartFile("files", files.getBytes());
MockMultipartFile key = new MockMultipartFile("fileKey", fileKey.getBytes());
mockMvc.perform(fileUpload("/")
.file(blob)
.file(key))
.andDo(print())
.andExpect(status().isOk());如您所见,我使用了fileUpload。但在过去,我尝试将post与content或requestAttr结合使用,因为它们都不起作用。
我认为当前的代码是我尝试过的最接近答案的代码,但是不能再接近了。
奇怪的是,真正正在使用的API与它们几乎是一样的。在客户端,用户向请求发送一个新的FormData()对象,服务器可以正确地获取数据。
服务器端代码如下。
@RequestMapping(value = "/api/{variable}", method = RequestMethod.POST)
public ResponseEntity<Object> apiMethod(
@PathVariable int variable,
@RequestPart("dto1") DTO1 dto1,
@RequestPart("dto2") DTO2 dto2,
@RequestPart("file") Map<String, Object> file)"file“部分由”文件名“键及其blob值编码的base64组成。
例如,{"hello.txt": "SGVsbG8gd29ybGQh"}
使用@RequestPart
null.
post / data - file、content、requestAttr,但它们发送的是-post/ data - file、content、requestAttr,但它们抛出了MultipartException.。
multipart,因为系统使用的是Spring.的低版本。


谢谢!
发布于 2020-09-18 04:57:13
感谢@borino对我的问题发表评论,我得到了问题的线索。
使用fileUpload测试带有@RequestPart参数的API是肯定的。
在这种情况下,它是由内容类型引起的。我声明MockMultipartFile没有contentType。
MockMultipartFile blob = new MockMultipartFile("files", files.getBytes());
MockMultipartFile key = new MockMultipartFile("fileKey", fileKey.getBytes());但是API的参数有一个类型,Map<String,Object>和String。正如@borino对我说的那样,我更改了MockMultipartFile的构造函数,以确保contentType有效!
MockMultipartFile blob = new MockMultipartFile("files", "", "application/json", files.getBytes());
MockMultipartFile key = new MockMultipartFile("fileKey", "", "application/json", fileKey.getBytes());当您遇到像我这样的问题时,只需添加contentType即可。谢谢!
https://stackoverflow.com/questions/63915037
复制相似问题