Testing ASP.NET Web API Multipart Form Data File upload
asp.net-web-api, http-post, nunit, unit-testing
Solution
After spending a bit of time looking into WebClient I was able to come up with this:
try
{
var imageFile = Path.Combine("dir", "fileName");
WebClient webClient = new WebClient();
byte[] rawResponse = webClient.UploadFile(string.Format("{0}/api/values/", "http://localhost:12345/"), imageFile);
Console.WriteLine("Sever Response: {0}", System.Text.Encoding.ASCII.GetString(rawResponse)); // for debugging purposes
Console.WriteLine("File Upload was successful");
}
catch (WebException wexc)
{
Console.WriteLine("Failed with an exception of " + wexc.Message);
// anything other than 200 will trigger the WebException
}
Problem
I am trying to use N-UNIT to test my web API application but I am unable to find a proper way to test my file upload method. Which would be the best approach to test the method? Web API Controller: ``` [AcceptVerbs("post")] public async Task<HttpResponseMessage> Validate() { // Check if the request contains multipart/form-data. if (!Request.Content.IsMimeMultipartContent()) { return Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType,"please submit a valid request"); } var provider = new MultipartMemoryStreamProvider(); // this loads the file into memory for later on processing try { await Request.Content.ReadAsMultipartAsync(provider); var resp = new HttpResponseMessage(HttpStatusCode.OK); foreach (var item in provider.Contents) { if (item.Headers.ContentDisposition.FileName != null) { Stream stream = item.ReadAsStreamAsync().Result; // do some stuff and return response resp.Content = new StringContent(result, Encoding.UTF8, "application/xml"); //text/plain "application/xml" return resp; } } return resp; } catch (System.Exception e) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); } } ```