我如何testingModelState?

我如何testingController.ViewData.ModelState ? 我宁愿没有任何模拟框架。

当然,如果您正在为数据使用存储库模式,则不必使用模拟。

一些例子: http : //www.singingeels.com/Articles/Test_Driven_Development_with_ASPNET_MVC.aspx

 // Test for required "FirstName". controller.ViewData.ModelState.Clear(); newCustomer = new Customer { FirstName = "", LastName = "Smith", Zip = "34275", }; controller.Create(newCustomer); // Make sure that our validation found the error! Assert.IsTrue(controller.ViewData.ModelState.Count == 1, "FirstName must be required."); 
 //[Required] //public string Name { get; set; } //[Required] //public string Description { get; set; } ProductModelEdit model = new ProductModelEdit() ; //Init ModelState var modelBinder = new ModelBindingContext() { ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType( () => model, model.GetType()), ValueProvider=new NameValueCollectionValueProvider( new NameValueCollection(), CultureInfo.InvariantCulture) }; var binder=new DefaultModelBinder().BindModel( new ControllerContext(),modelBinder ); ProductController.ModelState.Clear(); ProductController.ModelState.Merge(modelBinder.ModelState); ViewResult result = (ViewResult)ProductController.CreateProduct(null,model); Assert.IsTrue(result.ViewData.ModelState["Name"].Errors.Count > 0); Assert.True(result.ViewData.ModelState["Description"].Errors.Count > 0); Assert.True(!result.ViewData.ModelState.IsValid); 

要testingWeb API,请使用控制器上的validation方法:

 var controller = new MyController(); controller.Configuration = new HttpConfiguration(); var model = new MyModel(); controller.Validate(model); var result = controller.MyMethod(model); 

添加上面的很好的答案,看看这个控制器类中保护TryValidateModel方法的奇妙使用。

只需创build一个从控制器inheritance的testing类,并将您的模型传递给TryValidateModel方法。 这是链接: http : //blog.icanmakethiswork.io/2013/03/unit-testing-modelstate.html

John Reilly和Marc Talary对此解决scheme充满信心。