Reputation: 231
I am trying to mock a MultipartFile and I want to create the mock with a stream that I create in the test
I've tries with a file without much luck either. Here is what I have tried so far
FileInputStream stream = new
FileInputStream("MOCK_file.xlsm");
MultipartFile f1 = new MockMultipartFile("file1",stream);
MultipartFile[] files = {f1};
return files;
I get a fileNotFoundException. Where should I put my file in my Maven project so the unit tests can find the file?
-- OR --
How do I just create a stream in code without the use of a file?
Upvotes: 2
Views: 13724
Reputation: 1052
Even better you can mock only the MultipartFile
and you will not be needing the InputStream
at all.
To do so you only need to do mock(MultiPartFile.class)
and then define what each function will do
For example if you use the name
final MultipartFile mockFile = mock(MultipartFile.class);
when(mockFile.getOriginalFilename()).thenReturn("CoolName");
This way you wont have to bother with actual files neither unexpected responses as you will be defining them
Upvotes: 5
Reputation: 7404
Put the file in
src/test/resources/MOCK_file.xlsm
Read from JUnit class with:
InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("MOCK_file.xlsm");
Upvotes: 1
Reputation: 30285
How do I just create a stream in code without the use of a file?
You could use a ByteArrayInputStream
to inject mock data. It's pretty straightforward for a small amount of data:
byte[] data = new byte[] {1, 2, 3, 4};
InputStream stream = new ByteArrayInputStream(data);
Otherwise, you need to figure out what directory is your code running from, which is something that depends on how it's being run. To help with that you could print the user.dir
system property, which tells you the current directory:
System.out.println(System.getProperty("user.dir"));
Alternatively, you can use a full path, rather than a relative one to find the file.
Upvotes: 1