NSubstitute Mock MVC ActionResult属性

时间:2018-02-08 10:50:56

标签: c# asp.net-mvc mocking nsubstitute

我希望在测试期间调用与控制器操作关联的属性。

E.g。代码

[TestMethod]
    public void UserRegistersWithNonMatchingPasswords()
    {
        var model = GetModel();

        var controller= GetController();
        controller.Register(model); //This is an ActionResult method

        AccountRepository
            .DidNotReceive()
            .IsAccountExists(Arg.Any<string>());

        AccountRepository
            .DidNotReceive()
            .CreateUser(Arg.Any<string>(), Arg.Any<string>());

    }

现在注册方法看起来像

    [HttpPost]
    [ValidateModel]
    public ActionResult Register(Model model)
    {
        //The validate model attribute checks the ModelState.IsValid and returns if it's not valid, so any code in the method shouldn't run because of the failed validation.

         IsAccountExists();
         CreateUser();
    }

ValidateModel属性代码(来自Sitecore Habitat框架)

    public class ValidateModelAttribute : ActionFilterAttribute
  {
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      var viewData = filterContext.Controller.ViewData;

      if (!viewData.ModelState.IsValid)
      {
        filterContext.Result = new ViewResult
                               {
                                 ViewData = viewData,
                                 TempData = filterContext.Controller.TempData
                               };
      }
    }
  }

然而,它是调用这些属性的MVC框架,所以我想知道如何让NSubsitute调用它,因为它忽略了属性。感谢。

0 个答案:

没有答案