0
我想单元测试文件上传,但似乎缺少的东西。嘲笑Request.Files测试空文件上传
控制器包含在httpPost处理这个相当标准块:
foreach (string file in Request.Files) {
var postedFile = Request.Files[file] as HttpPostedFileBase;
if (postedFile.ContentLength == 0)
continue;
var fileName = "~/Uploaded/" + Path.GetFileName(postedFile.FileName);
postedFile.SaveAs(Server.MapPath(fileName));
}
对于单元测试我使用商务部:
var mock = new Mock<ControllerContext>();
mock.Setup(p => p.HttpContext.Request.Files.Count).Returns(0);
// also tried unsuccessfully:
// var collection = new Mock<HttpFileCollectionBase>();
// mock.Setup(p => p.HttpContext.Request.Files).Returns(collection.Object);
// mock.Setup(p => p.HttpContext.Request.Files.AllKeys).Returns(new string[] {});
var controller = CreateReportsController();
controller.ControllerContext = mock.Object;
我的希望是,嘲笑的情况下将模拟一个有效的请求没有任何文件上传。相反,它会在foreach语句中出现nullreference异常。我可以看到为什么,因为我没有真正设置Request.Files,但我不知道如何做得更好。
那么,如何正确配置moc上下文?
感谢, 达菲