HttpPostedFileBase 如何做单元测试

ASP.NET MVC3 中一个Controller的Action需要HttpPostedFileBase,在做单元测试时,怎么为这个参数实例化一个文件呀?

一只斗牛犬
浏览 364回答 1
1回答

繁花不似锦

建议使用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);
打开App,查看更多内容
随时随地看视频慕课网APP