Spring Boot Failing中的MultipartFile上传测试

编程入门 行业动态 更新时间:2024-10-23 17:27:58
Spring Boot Failing中的MultipartFile上传测试 - 不确定原因(MultipartFile upload test in Spring Boot Failing - not sure why)

我正在控制器中测试POST方法,该控制器通过MultipartFile处理图像上传。 允许为空,但如果存在文件,则应将其上传。 我写了一个单元测试,以确保它有效,但测试失败,返回404,我不知道为什么 - 可能是因为我不擅长阅读正在发生的事情。 这是测试:

@Test public void saveAnEntryWhenPOSTNewUserWithAPicture() throws Exception { MockMultipartFile multiPFImage = new MockMultipartFile("ABCPicture", "abcpic.png", "img/png", "Generate bytes to simulate a picture".getBytes()); mockMvc.perform(MockMvcRequestBuilders.fileUpload("/newcontact") .file(multiPFImage) .param("userId", "12345") .param("name", "Picture Uploader User")) .andExpect(status().isOk()) .andExpect(content().string(containsString("savedContact"))); }

这是运行该测试产生的堆栈跟踪:

MockHttpServletRequest: HTTP Method = POST Request URI = /newContact Parameters = {userId=[12345], name=[John Smith]} Headers = {} Handler: Type = app.controllers.AdditiveController Method = public java.lang.String app.controllers.AdditiveController.createNewContact(app.models.dto.ContactDTO) Async: Async started = false Async result = null Resolved Exception: Type = null ModelAndView: View name = null View = null Model = null FlashMap: Attributes = null MockHttpServletResponse: Status = 200 Error message = null Headers = {Content-Type=[text/plain;charset=UTF-8], Content-Length=[12]} Content type = text/plain;charset=UTF-8 Body = savedContact Forwarded URL = null Redirected URL = null Cookies = [] MockHttpServletRequest: HTTP Method = GET Request URI = /newContact Parameters = {} Headers = {} Handler: Type = app.controllers.AdditiveController Method = public app.models.dto.ContactDTO app.controllers.AdditiveController.sendNewContactForm(org.springframework.ui.Model) Async: Async started = false Async result = null Resolved Exception: Type = null ModelAndView: View name = null View = null Model = null FlashMap: Attributes = null MockHttpServletResponse: Status = 200 Error message = null Headers = {Content-Type=[application/json;charset=UTF-8]} Content type = application/json;charset=UTF-8 Body = {"userId":null,"contactId":null,"name":null,"email":null,"bday":null,"address":null,"city":null,"state":null,"phones":null,"contactImg":null} Forwarded URL = null Redirected URL = null Cookies = [] MockHttpServletRequest: HTTP Method = POST Request URI = /newcontact Parameters = {userId=[12345], name=[Picture Uploader User]} Headers = {Content-Type=[multipart/form-data;charset=UTF-8]} Handler: Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler Async: Async started = false Async result = null Resolved Exception: Type = null ModelAndView: View name = null View = null Model = null FlashMap: Attributes = null MockHttpServletResponse: Status = 404 Error message = null Headers = {} Content type = null Body = Forwarded URL = null Redirected URL = null Cookies = [] java.lang.AssertionError: Status Expected :200 Actual :404 <Click to see difference> at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54) at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81) at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:665) at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171) at app.controllers.AdditiveControllerShould.saveAnEntryWhenPOSTNewUserWithAPicture(AdditiveControllerShould.java:72) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

编辑:

这是正在测试的控制器方法:

@PostMapping(path = "/newContact") public String createNewContact(@ModelAttribute ContactDTO newContact) { Contact contact = new Contact(newContact.getUserId(), newContact.getName()); setOptionalContactFields(contact, newContact); contactDAO.save(contact); // contactId automatically generated here (via SQL autoIncrement) newContact.setContactId(contact.getContactId()); // update the newContact to include the contactId if (newContact.getContactImg() !=null ) { uploadContactProfileImg(newContact); // handles actual saving of image to persistence layer } return "savedContact"; // assumes template that can display all fields of a Contact will be returned }

任何有识之士将不胜感激。

I'm testing a POST method in a controller that handles the uploading of an image via a MultipartFile. It is allowed to be empty, but if there is a file present, it should upload it. I wrote a Unit test to make sure it worked, but the test is failing, returning a 404, and I'm not sure why - probably because I'm not adept at reading what's happening. Here's the test:

@Test public void saveAnEntryWhenPOSTNewUserWithAPicture() throws Exception { MockMultipartFile multiPFImage = new MockMultipartFile("ABCPicture", "abcpic.png", "img/png", "Generate bytes to simulate a picture".getBytes()); mockMvc.perform(MockMvcRequestBuilders.fileUpload("/newcontact") .file(multiPFImage) .param("userId", "12345") .param("name", "Picture Uploader User")) .andExpect(status().isOk()) .andExpect(content().string(containsString("savedContact"))); }

And here's the stack trace that results from running that test:

MockHttpServletRequest: HTTP Method = POST Request URI = /newContact Parameters = {userId=[12345], name=[John Smith]} Headers = {} Handler: Type = app.controllers.AdditiveController Method = public java.lang.String app.controllers.AdditiveController.createNewContact(app.models.dto.ContactDTO) Async: Async started = false Async result = null Resolved Exception: Type = null ModelAndView: View name = null View = null Model = null FlashMap: Attributes = null MockHttpServletResponse: Status = 200 Error message = null Headers = {Content-Type=[text/plain;charset=UTF-8], Content-Length=[12]} Content type = text/plain;charset=UTF-8 Body = savedContact Forwarded URL = null Redirected URL = null Cookies = [] MockHttpServletRequest: HTTP Method = GET Request URI = /newContact Parameters = {} Headers = {} Handler: Type = app.controllers.AdditiveController Method = public app.models.dto.ContactDTO app.controllers.AdditiveController.sendNewContactForm(org.springframework.ui.Model) Async: Async started = false Async result = null Resolved Exception: Type = null ModelAndView: View name = null View = null Model = null FlashMap: Attributes = null MockHttpServletResponse: Status = 200 Error message = null Headers = {Content-Type=[application/json;charset=UTF-8]} Content type = application/json;charset=UTF-8 Body = {"userId":null,"contactId":null,"name":null,"email":null,"bday":null,"address":null,"city":null,"state":null,"phones":null,"contactImg":null} Forwarded URL = null Redirected URL = null Cookies = [] MockHttpServletRequest: HTTP Method = POST Request URI = /newcontact Parameters = {userId=[12345], name=[Picture Uploader User]} Headers = {Content-Type=[multipart/form-data;charset=UTF-8]} Handler: Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler Async: Async started = false Async result = null Resolved Exception: Type = null ModelAndView: View name = null View = null Model = null FlashMap: Attributes = null MockHttpServletResponse: Status = 404 Error message = null Headers = {} Content type = null Body = Forwarded URL = null Redirected URL = null Cookies = [] java.lang.AssertionError: Status Expected :200 Actual :404 <Click to see difference> at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54) at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81) at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:665) at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171) at app.controllers.AdditiveControllerShould.saveAnEntryWhenPOSTNewUserWithAPicture(AdditiveControllerShould.java:72) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Edit:

Here is the controller method which is being tested:

@PostMapping(path = "/newContact") public String createNewContact(@ModelAttribute ContactDTO newContact) { Contact contact = new Contact(newContact.getUserId(), newContact.getName()); setOptionalContactFields(contact, newContact); contactDAO.save(contact); // contactId automatically generated here (via SQL autoIncrement) newContact.setContactId(contact.getContactId()); // update the newContact to include the contactId if (newContact.getContactImg() !=null ) { uploadContactProfileImg(newContact); // handles actual saving of image to persistence layer } return "savedContact"; // assumes template that can display all fields of a Contact will be returned }

Any insight would be greatly appreciated.

最满意答案

我发现你有错误类型MockMvcRequestBuilders.fileUpload("/newcontact")

应该是MockMvcRequestBuilders.fileUpload("/newContact")

附加:您的DTO中存在拼写错误

public class ContactDTO { private MultipartFile conactImg; }

请求多部分名称应该与DTO相同, ABCPicture应该是conactImg

I found out that you have mistype MockMvcRequestBuilders.fileUpload("/newcontact")

should be MockMvcRequestBuilders.fileUpload("/newContact")

Additional: There's a typo in your DTO

public class ContactDTO { private MultipartFile conactImg; }

request multipart name should be the same with DTO, ABCPicture should be conactImg

更多推荐

本文发布于:2023-08-01 18:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1363759.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上传   测试   Boot   Spring   MultipartFile

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!