【发布时间】:2014-01-11 21:54:04
【问题描述】:
我正在使用以下方法通过 ASP.NET Web API 控制器上传文件。
[System.Web.Http.HttpPost]
public HttpResponseMessage UploadFile()
{
HttpResponseMessage response;
try
{
int id = 0;
int? qId = null;
if (int.TryParse(HttpContext.Current.Request.Form["id"], out id))
{
qId = id;
}
var file = HttpContext.Current.Request.Files[0];
int filePursuitId = bl.UploadFile(qId, file);
}
catch (Exception ex)
{
}
return response;
}
在我的单元测试中,我在调用 UploadFile 操作之前手动创建了一个 HTTPContext 类:
var request = new HttpRequest("", "http://localhost", "");
var context = new HttpContext(request, new HttpResponse(new StringWriter()));
HttpContext.Current = context;
response = controller.UploadFile();
很遗憾,我无法将自定义值添加到 Form 集合,因为它是只读的。我也无法更改 Files 集合。
有没有办法在单元测试期间向Request 的Form 和Files 属性添加自定义值以添加所需的数据(id 和文件内容)?
【问题讨论】:
标签: c# asp.net unit-testing asp.net-mvc-4