I recently had a problem where I needed to unit test an ApiController action that read data off of the controller’s request object, in other words, something that looks like this:
The real-world action receives a multipart/form-data request (a form), which contains an uploaded file as one of its fields. Reading the form fields and file data from the ‘Request’ object is not particularly difficult, but figuring out how to mock the HttpRequestMessage was a non-trivial exercise, which is why I thought I’d share it here.
Note: there is a distinct difference between how this gets done for ASP.NET Web API and how it can be done for MVC (which is better supported on StackOverflow, etc from what I could find)
The final solution is actually reasonably straightforward, but it took me a long time to figure out, so here goes
Another note: the unit testing framework used is NUnit and the assumption here is that you already have your test environment set up, with a class to contain the tests for your ApiController
First, I created a helper method in my test class to build the mocked MultiPartFormDataContent
Note: The ‘boundary’ can be anything you choose as long as it doesn’t appear in the form data (see W3.org for more info on multipart/form-data)
Now that you have the MultiPartFormDataContent mock set up, the controller under test can then be created like this (for example):
And voila! Controller action relying on ‘Request’ data can now be tested.