Testing ModelState is always valid in asp.net mvc

后端 未结 7 1100
野趣味
野趣味 2020-12-09 16:29

When testing my controller\'s actions the ModelState is always valid.

public class Product
{
    public int Id { get; set; }

    [Required]
    [StringLengt         


        
相关标签:
7条回答
  • 2020-12-09 17:03

    On another note. You should actually test what the controller returns and that the returned ActionResult is what you expect. Testing the ModelBinder should be done separately.

    Let's say, you want to switch to a custom model binder. You could reuse the ModelBinder tests to the new ModelBinder you're creating. If your business rules remain the same, you should be able to directly reuse the same tests. However, if you mix your Controller test and ModelBinder tests and the test fails, you don't know if the problem is in the Controller or the ModelBinder.

    Let's say you test your model binding something like this:

    [Test]
    public void Date_Can_Be_Pulled_Via_Provided_Month_Day_Year()
    {
        // Arrange
        var formCollection = new NameValueCollection { 
            { "foo.month", "2" },
            { "foo.day", "12" },
            { "foo.year", "1964" }
        };
    
        var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
        var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(FwpUser));
    
        var bindingContext = new ModelBindingContext
        {
            ModelName = "foo",
            ValueProvider = valueProvider,
            ModelMetadata = modelMetadata
        };
    
        DateAndTimeModelBinder b = new DateAndTimeModelBinder { Month = "month", Day = "day", Year = "year" };
        ControllerContext controllerContext = new ControllerContext();
    
        // Act
        DateTime result = (DateTime)b.BindModel(controllerContext, bindingContext);
    
        // Assert
        Assert.AreEqual(DateTime.Parse("1964-02-12 12:00:00 am"), result);
    }
    

    Now that you KNOW, your model is bound right, you can continue testing the Model with your controller in a separate test to check if it returns you the correct result. Additionally, you can use the bound model values to test your Validation Attributes.

    This way you can get a full set of tests which will reveal, if your application blows up, in which level it actually does that. ModelBinding, Controller or Validation.

    0 讨论(0)
提交回复
热议问题