1

I have file names test.csv ,test.xml ,test.text on my classpath(src/main/resources) folder.

I am creating Mutlipart for my Junit test case as follows :

MultipartFile multipartFile = new MockMultipartFile("test.csv","test.csv","text/csv",
                new FileInputStream(new File("test.csv")));

This is working fine.

However when I am trying below code for XMl,it gives FileNotFoundException.

MultipartFile multipartFile = new MockMultipartFile("test.xml","test.xml","text/xml",
                    new FileInputStream(new File("test.xml")));

Can anyone pls let me know,what can be issue?

javaguy
  • 927
  • 2
  • 16
  • 37

2 Answers2

2

Got resolution as below :

MockMultipartFile   mockitoMultipartFile = new MockMultipartFile("test.xml","test.xml","text/xml",
                this.getClass().getClassLoader()
                .getResourceAsStream("test.xml"));
javaguy
  • 927
  • 2
  • 16
  • 37
0

Since you are mocking, you should use like this.

MockMultipartFile mockMultipartFile = new MockMultipartFile("test.xml","test.xml","text/xml",
                    new FileInputStream(new File("test.xml")));

The actual structure should be like this.

MockMultipartFile mockMultipartFile = new MockMultipartFile("test", "test.xml", <XML MEDIA TYPE>,
      "String contents".getBytes()));

For more reference, see below the links. https://www.codota.com/code/java/classes/org.springframework.mock.web.MockMultipartFile

Using Spring MVC Test to unit test multipart POST request

Sambit
  • 7,625
  • 7
  • 34
  • 65
  • Thanks Sambit but it did not help.Still gettin same exception. – javaguy Jul 14 '19 at 15:37
  • Can you provide the exception stack details ? – Sambit Jul 14 '19 at 15:41
  • java.lang.Exception: Unexpected exception, expected but was at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) – javaguy Jul 14 '19 at 15:44
  • Actually,I dont have String content.I have a file,which needs to be read,so I am using following constructor of MockitoMultipartFile: – javaguy Jul 14 '19 at 15:59
  • MockMultipartFile( String name,String originalFilename,String contentType, InputStream contentStream) – javaguy Jul 14 '19 at 16:00