【发布时间】:2011-02-18 06:45:51
【问题描述】:
如何对自定义 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", 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; }
}
问题?在 MagicBinder 中,bindingContext.Model 为空。如果我尝试设置它 bindingContext.Model = new Foo().我收到一个异常说它已被弃用,我应该设置 ModelMetadata。
那么我该如何构造一个 ModelMetadata 呢?它甚至不能被嘲笑。
【问题讨论】:
-
仅供未来读者注意,TryGetValue 不再可用(MVC1 后):stackoverflow.com/questions/4149805/…
标签: asp.net-mvc-3