在 ASP.NET MVC (1.0) 中针对 HTTP 上下文测试自定义 ModelBinder
我正在尝试对自定义模型绑定器进行单元测试 - 具体来说,我想看看它如何响应在 Request.Form 和 Request.QueryString 集合中提交的各种(可能冲突的)值 - 即,如果我在表单中提交一个值查询字符串中的另一个(是的,是的,我知道,这是邪恶的,但我希望测试覆盖率,以防万一发生)我可以准确验证哪个将绑定到模型。
为了做到这一点,我想模拟/伪造 HTTP 上下文,然后调用模型绑定器并查看实际返回的内容。我看过几篇关于测试 ModelBinder 的文章,但它们都使用自定义 ValueProvider,而我实际上想测试 MVC 与 Form/Request 集合交互的方式。
我有什么想法可以模拟这些集合,然后使我的模型绑定器在我的单元测试中使用基于此模拟 HTTP 上下文的“默认”ValueProvider 吗?这是 ASP.NET MVC 1.0 上的。谢谢。
I'm trying to unit test a custom model binder - specifically, I want to see how it responds to various (possibly conflicting) values being submitted in the Request.Form and Request.QueryString collections - i.e. if I submit one value in the form and another in the querystring (yeah, yeah, I know, this is evil, but I want test coverage in case it happens) I can validate exactly which one will be bound to the model.
In order to do this, I'd like to mock/fake the HTTP context, and then invoke the model binder and see what is actually returned. I've seen several posts about testing ModelBinders, but all of them use a custom ValueProvider, whereas I actually want to test the way MVC is interacting with Form/Request collections.
Any ideas how I can mock these collections and then cause my model binder to use the 'default' ValueProvider based on this mocked HTTP context in my units tests? This is on ASP.NET MVC 1.0. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
成功了 - 解决方案是模拟 ControllerContext,然后构造一个新的 System.Web.Mvc.ValueProviderDictionary 并将模拟的控制器上下文传递到构造函数中,如下所示:
Nailed it - the solution is to mock the ControllerContext, and then construct a new System.Web.Mvc.ValueProviderDictionary and pass your mocked controller context into the constructor, as follows: