显然,我没有正确使用此测试装置。我的servlet在tomcat中工作得很好,但是当我尝试使用此模拟程序时,找不到多部分边界。“该请求被拒绝,因为未找到多部分边界”。
此处有一个答案,显示了如何通过文本文件使用此答案,但该答案明确设置了边界字符串并将该文件嵌入为test。我认为我不需要手动处理诸如 ockerrequest.addFile (…)之类的方法
我在这里没有设置什么或者我做错了什么?
@org.testng.annotations.Test public void testDoPost() throws Exception { MockMultipartFile file = new MockMultipartFile("test.zip", "test.zip", "application/zip", MyServletTest.class.getResourceAsStream("/test.zip")); MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest(); mockRequest.addFile(file); mockRequest.set mockRequest.setMethod("POST"); mockRequest.setParameter("variant", "php"); mockRequest.setParameter("os", "mac"); mockRequest.setParameter("version", "3.4"); MockHttpServletResponse response = new MockHttpServletResponse(); new MyServletTest().doPost(mockRequest, response); // BOOM ! }
这是例外
Caused by: blablah: the request was rejected because no multipart boundary was found
您需要设置边界。
这里对边界是什么有很好的解释http://codingdict.com/questions/144876
要解决您的问题,请尝试以下代码。
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.apache.commons.lang.ArrayUtils; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockMultipartFile; import org.springframework.mock.web.MockMultipartHttpServletRequest; public class FileUploadTest { public void testDoPost() throws IOException { Path path = Paths.get("c:\\temp\\test.zip"); byte[] data = Files.readAllBytes(path); MockMultipartFile file = new MockMultipartFile("test.zip", "test.zip", "application/zip", data); MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest(); String boundary = "q1w2e3r4t5y6u7i8o9"; mockRequest.setContentType("multipart/form-data; boundary="+boundary); mockRequest.setContent(createFileContent(data,boundary,"application/zip","test.zip")); mockRequest.addFile(file); mockRequest.setMethod("POST"); mockRequest.setParameter("variant", "php"); mockRequest.setParameter("os", "mac"); mockRequest.setParameter("version", "3.4"); MockHttpServletResponse response = new MockHttpServletResponse(); new FileUpload().doPost(mockRequest, response); } public byte[] createFileContent(byte[] data, String boundary, String contentType, String fileName){ String start = "--" + boundary + "\r\n Content-Disposition: form-data; name=\"file\"; filename=\""+fileName+"\"\r\n" + "Content-type: "+contentType+"\r\n\r\n";; String end = "\r\n--" + boundary + "--"; // correction suggested @butfly return ArrayUtils.addAll(start.getBytes(),ArrayUtils.addAll(data,end.getBytes())); } }