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();
}
EDIT:
Sorry i completely forgot to include dependancy injection code. I am using SimpleInjector.
So i have now added this to it
// return current httpContext
container.RegisterPerWebRequest<HttpContext>(() => HttpContext.Current);
Which i cannot yet test because i still cannot work out how to mock httpContext. my controller is now created like so
private IImageService _service;
private HttpContext _httpContext;
public ImageController(IImageService service, HttpContext httpContext)
{
_service = service;
_httpContext = httpContext;
}
And i have changed HttpContext.Current to _httpContext.
But how can i create a mock of HttpContext??