Testing ModelState is always valid in asp.net mvc

后端 未结 7 1099
野趣味
野趣味 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 16:44

    If you want to test your validation action's behavior you could simply add ModelStateError:

    ModelState.AddModelError("Password", "The Password field is required");
    
    0 讨论(0)
  • 2020-12-09 16:46

    Validation happens when the posted data is bound to the view model. The view model is then passed into the controller. You are skipping part 1 and passing a view model straight into a controller.

    You can manually validate a view model using

    System.ComponentModel.DataAnnotations.Validator.TryValidateObject()
    
    0 讨论(0)
  • 2020-12-09 16:48
    1. Create Instance of your controller class.
    2. Add model state and call After adding model state
    3. the modelState always give false

      controller.ModelState.AddModelError("key", "error message");
      
      var invalidStateResult = _controller.Index();
      
      Assert.IsNotNull(invalidStateResult);
      
    0 讨论(0)
  • 2020-12-09 16:52

    I have come across the same issue and while the accepted answer here did solve the "no-validation"-issue, it did leave me with a big negative aspect: it would throw an exception when there were validation errors instead of simply setting ModelState.Invalid to false.

    I only tested this in Web Api 2 so I don't know what projects will have this available but there is a method ApiController.Validate(object) which forces validation on the passed object and only sets the ModelState.IsValid to false. Additionally you'll also have to instantiate the Configuration property.

    Adding this code to my unit test allowed it to work:

    userController.Configuration = new HttpConfiguration();
    userController.Validate(addressInfo);
    
    0 讨论(0)
  • 2020-12-09 16:56

    Try controller.ViewModel.ModelState.IsValid instead of controller.ModelState.IsValid.

    0 讨论(0)
  • 2020-12-09 16:57

    Use controller.UpdateModel or controller.TryUpdateModel to use the controller's current ValueProvider to bind some data and trigger model binding validation prior to checking if the ModelState.IsValid

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