When testing my controller\'s actions the ModelState is always valid.
public class Product
{
public int Id { get; set; }
[Required]
[StringLengt
If you want to test your validation action's behavior you could simply add ModelStateError:
ModelState.AddModelError("Password", "The Password field is required");
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()
the modelState always give false
controller.ModelState.AddModelError("key", "error message");
var invalidStateResult = _controller.Index();
Assert.IsNotNull(invalidStateResult);
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);
Try controller.ViewModel.ModelState.IsValid instead of controller.ModelState.IsValid.
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