Upload CommonsMultipartFile with jUnit and Spring-Test

One of my recent endeavors was to upload a file from a unit test without mocking the process and to simulate the behavior of a form submission.

Of course the web is full of solutions on how to achieve this if you actually have a form…but if the form is gone…well good luck there.

I’ve tried my luck on stackoverflow and unfortunately all i got was a NullPointerException:

Oh and how pleased i was to write the content above and try around 20 scenarios all with the same result. And then out of nowhere i found a post somewhere on the web which eventually led me to the solution i was seeking:

So guess what, writing simple stupid code actually works 🙂 and all the mumbo-jumbo code above was reduce to 3 lines of code that achieve the proper result. I also found out that by implementing the solution above, Spring will deserialize the FileSystemResource to a CommonsMultiPartFile without having to do any extra work 🙂