ASP.NET MVC3 中一個(gè)Controller的Action需要HttpPostedFileBase,在做單元測(cè)試時(shí),怎么為這個(gè)參數(shù)實(shí)例化一個(gè)文件呀?
1 回答

繁花不似錦
TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超4個(gè)贊
建議使用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 關(guān)注
- 378 瀏覽
添加回答
舉報(bào)
0/150
提交
取消