asp.net-mvc - 在 ASP.NET MVC 2 中测试模型绑定(bind)

标签 asp.net-mvc unit-testing modelbinders modelstate defaultmodelbinder

第一的;我知道我不需要测试 MVC 的内部,但我真的需要一个套件来测试流入我们系统的数据。

我希望在不模拟所有 HTTP 上下文的情况下如何测试 objectA(表单集合、字典、集合、对象等)是否符合 objectAModel?

我不想实例化我的 Controller 或调用 Action 。我只是想测试我的新对象是否使模型状态无效。

我希望我可以简单地写

var modelState = new ModelBindingContext<objectAModel>().validate(objectA);

最佳答案

布拉德威尔逊有一个 excellent post on DataAnnotations

How Do I Test It?

Using the DataAnnotations attributes for your models moves the validation out of the controller actions and into the model binder, which means your unit tests for your controller actions will be simplified.

When you’re writing tests for this, you need to verify three things:

  1. Is the DataAnnotationsModelBinder registered as the default binder? You’ll only do this once for the whole application, much like the route tests you would write.
  2. Is my model properly decorated with DataAnnotations attributes? You’ll end up writing tests for each validation attribute that you add to your model.
  3. Does my action method properly react when the model state is invalid? You’ll only need to write this once per action method.

关于asp.net-mvc - 在 ASP.NET MVC 2 中测试模型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1793905/

相关文章:

asp.net-mvc - ASP NET MVC 中的模型绑定(bind)数据库实体

asp.net-mvc-3 - MVC3 非顺序索引和 DefaultModelBinder

c# - dotnet-run 命令未按预期工作

c# - 单元测试自动映射器

unit-testing - 如何运行 :pending tests from command line?

c# - DataContract 模型绑定(bind)到 ASP.NET MVC 操作方法参数中的 JSON

javascript - 文件上传时 IE 中的访问被拒绝错误

c# - 如何获取 ASP.NET 应用程序路径?

asp.net-mvc - AngularJS - 循环中的单选按钮?

c# - 如何使用 Selenium 找到所有元素并将它们放入列表中?