How to mock ModelState.IsValid using the Moq framework?

后端 未结 3 1400
傲寒
傲寒 2020-12-24 04:19

I\'m checking ModelState.IsValid in my controller action method that creates an Employee like this:

[HttpPost]
public virtual ActionResult Crea         


        
3条回答
  •  星月不相逢
    2020-12-24 05:01

    The only issue I have with the solution above is that it doesn't actually test the model if I set attributes. I setup my controller this way.

    private HomeController GenerateController(object model)
        {
            HomeController controller = new HomeController()
            {
                RoleService = new MockRoleService(),
                MembershipService = new MockMembershipService()
            };
            MvcMockHelpers.SetFakeAuthenticatedControllerContext(controller);
    
            // bind errors modelstate to the controller
            var modelBinder = new ModelBindingContext()
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),
                ValueProvider = new NameValueCollectionValueProvider(new NameValueCollection(), CultureInfo.InvariantCulture)
            };
            var binder = new DefaultModelBinder().BindModel(new ControllerContext(), modelBinder);
            controller.ModelState.Clear();
            controller.ModelState.Merge(modelBinder.ModelState);
            return controller;
        }
    

    The modelBinder object is the object that test the validity of the model. This way I can just set the values of the object and test it.

提交回复
热议问题