简体   繁体   English

如何在ASP.NET MVC中使用Moq模拟HttpPostedFileBase

[英]How to mock HttpPostedFileBase using moq in ASP.NET MVC

My controller method: 我的控制器方法:

[HttpPost]
public ActionResult CreateTeam(Team model, HttpPostedFileBase upload)
{
     if (ModelState.IsValid)
     {
          if (upload != null)
          {
              // Get the file
              string fileName = System.IO.Path.GetFileName(upload.FileName);
              // Save the file in file сохраняем файл в папку Files в проекте
              upload.SaveAs(Server.MapPath("~/Images/NBAlogoImg/" + fileName));
          }
         teamRepository.CreatTeam(model);

         return RedirectToAction("Index", "Player");
    }

    return View(model);
}

My unit test method without upload image: 我的单元测试方法没有上传图片:

[TestMethod]
public void CanCreateTeam()
{
        //Arrange
        Mock<ITeamRepository> teamsMock = new Mock<ITeamRepository>();
        Team newTeam = new Team()
        {
            Id = 0,
            Name = "Chicago Bulls",
            Path = "CHI.jpg",
        };
        TeamController controller = new TeamController(teamsMock.Object);
        //Action
        ActionResult result = controller.CreateTeam(newTeam);
        teamsMock.Verify(m => m.CreatTeam(newTeam));
        //Assert
        Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
}

I don't have idea how make the right unit test for this action. 我不知道如何为此操作进行正确的单元测试。 However the action are working right without any problem. 但是,该操作正常进行,没有任何问题。

How in this test method add the functional for test of HttpPostedFileBase which upload the image? 在此测试方法中如何添加上传图像的HttpPostedFileBase测试功能?

First update your CreateTeam POST method as follows because there is a problem in upload.SaveAs(Server.MapPath("~/Images/NBAlogoImg/" + fileName)); 首先,如下更新您的CreateTeam POST方法,因为upload.SaveAs(Server.MapPath("~/Images/NBAlogoImg/" + fileName)); line. 线。

[HttpPost]
public ActionResult CreateTeam(Team model, HttpPostedFileBase upload)
{
     if (ModelState.IsValid)
     {
          if (upload != null)
          {
              // Get the file
              string fileName = System.IO.Path.GetFileName(upload.FileName);
              var fileUploadPath = Path.Combine(Server.MapPath("~/Images/NBAlogoImg/"),fileName);
              upload.SaveAs(fileUploadPath);
          }
         teamRepository.CreatTeam(model);

         return RedirectToAction("Index", "Player");
    }

    return View(model);
}

Then write your test method as follows: 然后编写您的测试方法,如下所示:

[TestMethod]
public void CanCreateTeam()
{
    //Arrange
    Mock<ITeamRepository> teamRepositoryMock = new Mock<ITeamRepository>();
    Team newTeam = new Team()
    {
        Id = 0,
        Name = "Chicago Bulls",
        Path = "CHI.jpg",
    };


    var httpContextMock = new Mock<HttpContextBase>();
    var serverMock = new Mock<HttpServerUtilityBase>();
    serverMock.Setup(x => x.MapPath("~/Images/NBAlogoImg/")).Returns(@"c:\work\app_data");
    httpContextMock.Setup(x => x.Server).Returns(serverMock.Object);

    var fileMock = new Mock<HttpPostedFileBase>();
    fileMock.Setup(x => x.FileName).Returns("file1.pdf");

    TeamController controller = new TeamController(teamRepositoryMock.Object);
    controller.ControllerContext = new ControllerContext(httpContextMock.Object, new RouteData(), controller);

    //Act
    ActionResult result = controller.CreateTeam(newTeam , fileMock.Object);

    //Assert
    fileMock.Verify(x => x.SaveAs(@"c:\work\app_data\file1.pdf"));
    Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
}

I have checked the above code in a test project and it works perfectly. 我已经在测试项目中检查了上面的代码,它可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM