asp.net mvc 3 - How to unit test modelbinder with ModelMetadata -
how unit test custom modelbinder?
here's code.
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; } }
and here test script.
[testmethod] public void testfoobinding() { var dict = new valueproviderdictionary(null) { {"number", new valueproviderresult("2", "2", null)}, {"test", new valueproviderresult("12", "12", null)}, }; 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; } }
problem? in magicbinder, bindingcontext.model null. if try set bindingcontext.model = new foo(). exception saying deprecated, , should set modelmetadata.
so how construct modelmetadata? can't mocked.
try this:
[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: }
Comments
Post a Comment