如何在 ASP.Net Mvc 3 中测试 ModelBinder
我正在尝试为自定义模型绑定器编写一些测试,但我的上帝发现这很难存根。我在网上找到的所有内容都与 ASP.Net Mvc 3 没有直接关系,或者示例往往非常不完整。
具体来说,我遇到的最大的障碍是与 bindingContext.ModelType - 显式设置它会引发一个(运行时)错误,该错误表明 setter 已过时,并且它是从 Model 参数推断出来的,但对我来说 Model 参数是并且应该为空!
I'm trying to write some tests for a custom modelbinder and my god is this turning out difficult to stub. None of the stuff I'm finding online relates directly to ASP.Net Mvc 3 or tends to have very incomplete examples.
Specifically, the biggest wall I'm hitting is with bindingContext.ModelType - setting it explcitly throws an (runtime) error that the setter is obsoleted and that it is inferred from the Model parameter but the Model parameter for me is and should be null!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Hanselman 在这里详细解释了这一点:
http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx
更新:上面的示例已过时。阅读这篇文章的评论!
Hanselman explains this in great detail here:
http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx
Update: The above sample is obsolete. Read the comments on this post!
托马斯&乔治,您必须在 ModelBindingContext 上设置值提供程序。下面是我的 HomeController Index 操作中的代码示例,该操作创建一个类型并使用默认模型绑定器来水合对象。这只是一个简化版本,在我的生产代码中,我实际上将一个参数放入控制器操作中,即类型,然后动态创建类型,当您想要将多个类型发送到单个控制器操作时效果很好。请注意,ValueProvider 和 ControllerContext 是控制器的属性。
Thomas & George, you have to set the value provider on the ModelBindingContext. Below is an example of code in my HomeController Index action that creates a type and uses the default model binder to hydrate the object. This is just a simplified version, in my production code I actually take a param into the controller action that is the type and then create the type dynamically on the fly, works great when you want to send more than one type to a single controller action. Notice that ValueProvider and ControllerContext are properties of the controller.