如何单元测试自定义的ModelBinder?
这是代码。
public class MagicBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext) { var boundModelObject = base.BindModel(controllerContext,bindingContext); var properties = bindingContext.ModelType.GetProperties().Where(a => a.CanWrite); foreach (var propertyInfo in properties) { object outValue = null; bindingContext.TryGetValue(propertyInfo.Name,propertyInfo.DeclaringType,out outValue); propertyInfo.SetValue(boundModelObject,outValue,null); } return boundModelObject; } }
这里是测试脚本。
[TestMethod] public void TestFooBinding() { var dict = new ValueProviderDictionary(null) { {"Number",new ValueProviderResult("2","2",null)},{"Test",new ValueProviderResult("12","12",}; var bindingContext = new ModelBindingContext() { ModelName = "foo",ValueProvider = dict}; var target = new MagicBinder(); Foo result = (Foo)target.BindModel(null,bindingContext); } public class Foo { public int Number { get; set; } public int Test { get; set; } }
问题?在MagicBinder中,bindingContext.Model为null。如果我尝试设置它
bindingContext.Model = new Foo()。我得到一个例外,称它已被弃用,我应该设置ModelMetadata。
那么如何构建ModelMetadata?它甚至不能被嘲笑。
解决方法
尝试这样:
[TestMethod] public void TestFooBinding() { // arrange var formCollection = new NameValueCollection { { "Number","2" },{ "Test","12" },}; var valueProvider = new NameValueCollectionValueProvider(formCollection,null); var Metadata = ModelMetadataProviders.Current.GetMetadataForType(null,typeof(Foo)); var bindingContext = new ModelBindingContext { ModelName = "",ValueProvider = valueProvider,ModelMetadata = Metadata }; var controllerContext = new ControllerContext(); var sut = new MagicBinder(); // act Foo actual = (Foo)sut.BindModel(controllerContext,bindingContext); // assert // TODO: }