Last week I wrote about how to upload a file from a website using Angular and .NET Core. Writing tests for this is mostly straightforward, but there’s a few gotchas that I thought I would write down for the next time I need to do this. The front end tests are pretty trivial – you can write some plumbing tests to make sure that things get sent to the right functions given certain conditions. You could also test to see that different parameters are set (if, for example, you show a spinner/loading icon when the upload button is clicked). In the example I wrote about last week, I didn’t have any of these, so I’m just going to skip the front end tests in this post.
Back End
On the back end, we need to be able to mock out an uploaded file and verify that we can read the contents and send it off to the _fileService.
I’m using xUnit, Moq and Autofac.Extras.Moq. Autofac.Extras.Moq automatically creates a loose mock for every dependency in the tree, letting you override just the pieces you want to (so you don’t have to manually create all of the mocks yourself every time). I’ve talked about it before in a different post.
The key here is to mock up the IFormCollection to contain a IFormFile with a stream representing the file information that you want, and add that to the HttpContext that will be provided to the controller when you invoke the method. All of that stuff happens automatically via the ASP.NET Core framework when a request comes in, so you need to do it yourself in the test.
Diego
Thanks Rob, great post, exactly what I was looking for.