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

时间:2019-01-24 08:02:01

标签: c# asp.net-mvc moq

我的控制器方法:

[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);
}

我的没有上传图片的单元测试方法:

[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));
}

我不知道如何为此操作进行正确的单元测试。但是,该操作正常进行,没有任何问题。

如何在此测试方法中添加用于上传图片的HttpPostedFileBase的测试功能?

1 个答案:

答案 0 :(得分:1)

首先更新您的CreateTeam POST方法,因为upload.SaveAs(Server.MapPath("~/Images/NBAlogoImg/" + fileName));行中存在问题。

[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);
}

然后编写您的测试方法,如下所示:

[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));
}

我已经在测试项目中检查了上面的代码,它运行完美。