Friday 20 July 2012

Unit test your modelbinders in MVC 3

Having an issue with this at work as the blokes at microsoft decided to depricate the modeltype in mvc 3 and make it settable via metadata.  fortunately, a solution exists that allows unit testing:


            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("formvariable", "formvalue");
            NameValueCollectionValueProvider collection = new NameValueCollectionValueProvider(nvc, null);


            var modelBindingContext = new ModelBindingContext
            {
                ModelName = "",
                ValueProvider = collection,
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(typeofmodelhere))
            };


            typeofmodel mymodel = typeofmodel.create(modelbindingcontext);
            Assert.AreEqual(value, model.x);


            Where the model takes in a modelbindingcontext and pulls out all of the values:


            public class typeofmodel
            { ...
                    public string x {get;set;}


                    public static create(ModelBindingContext context)
                   {
                             x = context.ValueProvider("");

Easy when you know how !