【发布时间】:2015-02-09 14:52:13
【问题描述】:
我开始为我们所有的控制器编写单元测试,似乎已经掌握了窍门,但现在我有点卡住了。我有以下控制器方法,我想为其编写单元测试,但有点迷失了。有人可以帮助并指出我正确的方向。我猜也许我需要稍微抽象一下方法,但不确定如何。
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();
}
编辑:
抱歉,我完全忘记了包含依赖注入代码。我正在使用 SimpleInjector。
所以我现在添加了这个
// return current httpContext
container.RegisterPerWebRequest<HttpContext>(() => HttpContext.Current);
我还不能测试,因为我仍然不知道如何模拟 httpContext。我的控制器现在是这样创建的
private IImageService _service;
private HttpContext _httpContext;
public ImageController(IImageService service, HttpContext httpContext)
{
_service = service;
_httpContext = httpContext;
}
我已将 HttpContext.Current 更改为 _httpContext。
但是我怎样才能创建一个 HttpContext 的模拟??
【问题讨论】:
标签: c# asp.net unit-testing asp.net-web-api moq