ModelState.IsValid always true when testing Controller in Asp.Net MVC Web Api

Thanks to this site, I found out the solution:

private void SimulateValidation(object model)
{
    // mimic the behaviour of the model binder which is responsible for Validating the Model
    var validationContext = new ValidationContext(model, null, null);
    var validationResults = new List<ValidationResult>();
    Validator.TryValidateObject(model, validationContext, validationResults, true);
    foreach (var validationResult in validationResults)
    {
        this.controller.ModelState.AddModelError(validationResult.MemberNames.First(), validationResult.ErrorMessage);
    }
}

And including one line in the test method like this:

public void MoviesController_Post_Without_Name()
{
    // Arrange
    var model = new MovieModel();
    model.Name = "";

    // Act
    SimulateValidation(model);
    var result = controller.Post(model);

    // Assert
    Assert.IsInstanceOfType(result, typeof(InvalidModelStateResult));
    Assert.AreEqual(6, controller.Get().Count());
}

Hope that helps someone, it would have saved me some hours hunting the web.


Your solution probably works, but a better way is using ApiController.Validate method.

public void MoviesController_Post_Without_Name()
{
    // Arrange
    var model = new MovieModel();
    model.Name = "";

    // Act
    controller.Validate(model);   //<---- use the built-in method
    var result = controller.Post(model);

    // Assert
    Assert.IsInstanceOfType(result, typeof(InvalidModelStateResult));
    Assert.AreEqual(6, controller.Get().Count());
}