ASP.NET MVC3 中一个Controller的Action需要HttpPostedFileBase,在做单元测试时,怎么为这个参数实例化一个文件呀?
1 回答
繁花不似锦
TA贡献1851条经验 获得超4个赞
建议使用Moq,参考代码(代码来源):
[TestMethod]
public void TestUpload() {
HomeController c = new HomeController();
Mock<ControllerContext> cc = new Mock<ControllerContext>();
UTF8Encoding enc = new UTF8Encoding();
Mock<HttpPostedFileBase> file1 = new Mock<HttpPostedFileBase>();
file1.Expect(d => d.FileName).Returns("test1.txt");
file1.Expect(d => d.InputStream).Returns(new MemoryStream(enc.GetBytes(Resources.UploadTestFiles.test1)));
Mock<HttpPostedFileBase> file2 = new Mock<HttpPostedFileBase>();
file2.Expect(d => d.FileName).Returns("test2.txt");
file2.Expect(d => d.InputStream).Returns(new MemoryStream(enc.GetBytes(Resources.UploadTestFiles.test2)));
cc.Expect(d => d.HttpContext.Request.Files.Count).Returns(2);
cc.Expect(d => d.HttpContext.Request.Files[0]).Returns(file1.Object);
cc.Expect(d => d.HttpContext.Request.Files[1]).Returns(file2.Object);
c.ControllerContext = cc.Object;
ActionResult r = c.Upload();
Assert.IsInstanceOfType(r, typeof(ContentResult));
Assert.AreNotEqual("Uploaded 2 files.<br/>\nFile test1.txt: Contents of test file 1<br/>\nFile test2.txt: Contents of test file 2<br/>", ((ContentResult)r).Content);
- 1 回答
- 0 关注
- 363 浏览
添加回答
举报
0/150
提交
取消