首页 新闻 会员 周边

HttpPostedFileBase 如何做单元测试

0
悬赏园豆:10 [已解决问题] 解决于 2012-05-08 09:38

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

Xiongpq的主页 Xiongpq | 初学一级 | 园豆:93
提问于:2012-03-23 11:12
< >
分享
最佳答案
0

建议使用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);
收获园豆:10
dudu | 高人七级 |园豆:30994 | 2012-03-23 15:08
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册