lundi 9 février 2015

Unit Test WebApi to upload image using Mock

I am starting to write unit tests for all our controllers and seem to be getting the hang of it, but now i am a bit stuck. I have the following controller method that i would like to write a unit test for but a am a bit lost. Can someone please help and point me in the right direction. I am guessing maybe i need to abstract the method slightly, but not sure how.



public async Task<IHttpActionResult> PostAsync()
{
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
// Get the uploaded image from the Files collection
var httpPostedFile = HttpContext.Current.Request.Files[0];

if (httpPostedFile != null)
{
// Validate the uploaded image, by only accepting certain file types and sizes
var validExtensions = new List<string>
{
".JPG", ".JPE", ".BMP", ".GIF", ".PNG"
};

if (!validExtensions.Contains(Path.GetExtension(httpPostedFile.FileName).ToUpperInvariant()))
{
return BadRequest();
}
else if (httpPostedFile.ContentLength > 2097152)
{
// file is over 2mb in size
return BadRequest();
}

// create a new image
var entity = new Image
{
Name = httpPostedFile.FileName,
Size = httpPostedFile.ContentLength,
Data = new ImageData
{
Content = new byte[httpPostedFile.ContentLength]
}
};

await httpPostedFile.InputStream.ReadAsync(entity.Data.Content, 0, httpPostedFile.ContentLength);

await _service.AddAsync(entity);

return Created<ImageModel>(Request.RequestUri, Mapper.Map<ImageModel>(entity));
}
}

return BadRequest();

}

Aucun commentaire:

Enregistrer un commentaire