模拟HttpPostedFileBase ASP MVC

时间:2018-03-16 14:57:28

标签: c# asp.net-mvc unit-testing mocking httppostedfilebase

尝试模拟上传文件。

这是控制器端

public ActionResult Index(HttpPostedFileBase file)
{
    if (file != null && file.ContentLength > 0)
        try
        {
            string path = Path.Combine(@"c:\work\",
             Path.GetFileName(file.FileName));
            file.SaveAs(path);
            ViewBag.Message = "File uploaded successfully";

这是单元测试方

[TestMethod]
public void TestMethod()
{
    Mock<ControllerContext> cc = new Mock<ControllerContext>();
    HomeController c = new HomeController()
    {
        ControllerContext = cc.Object
    };
    c.ControllerContext.RouteData = new RouteData();
    UTF8Encoding enc = new UTF8Encoding();
    Mock<HttpPostedFileBase> file1 = new Mock<HttpPostedFileBase>();
    var server = new Mock<HttpServerUtilityBase>();
    file1.SetupGet(d => d.FileName).Returns("listebv.txt");
    MemoryStream ms = new MemoryStream(enc.GetBytes(@"C:\work\listebv.txt"));
    file1.SetupGet(d => d.InputStream).Returns( ms);
    file1.SetupGet(d => d.ContentLength).Returns((int)ms.Length);
    file1.SetupGet(d => d.ContentType).Returns("text/plain");
    cc.SetupGet(d => d.HttpContext.Request.Files.Count).Returns(1);
    cc.SetupGet(d => d.HttpContext.Request.Files[0]).Returns(file1.Object);

    c.Index(file1.Object);

当我启动测试时,file.SaveAs (path)不起作用(没有创建文件) 并且没有返回错误

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

你正在传递一个模拟对象。该模拟对象实际上并不保存文件。您应该检查是否在模拟上调用了具有预期值的SaveAs。

file1.Verify(f => f.SaveAs(@"c:\work\listebv.txt"));