When testing my controller's actions the ModelState is always valid.
public class Product
{
public int Id { get; set; }
[Required]
[StringLength(10)]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
public decimal Price { get; set; }
}
And my controller.
public class ProductController : Controller
{
[HttpPost]
public ActionResult Create(Product product)
{
if (ModelState.IsValid)
{
// Do some creating logic...
return RedirectToAction("Display");
}
return View(product);
}
}
And test:
[Test]
public TestInvalidProduct()
{
var product = new Product();
var controller = new ProductController();
controller.Create(product);
//controller.ModelState.IsValid == true
}
Why the modelState is valid when the product doesn't have a name, Description and price?
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()
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);
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.
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
If you want to test your validation action's behavior you could simply add ModelStateError:
ModelState.AddModelError("Password", "The Password field is required");
Try controller.ViewModel.ModelState.IsValid instead of controller.ModelState.IsValid.