Search code examples
c#testingasp.net-web-apimodelstate

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


I have tried to make this work and made many google/stackoverflow searches with no luck at all.

I have a simple Model:

public class MovieModel
{
    public string Id { get; set; }

    [Required]
    [StringLength(100)]
    public string Name { get; set; }
}

A method in the controller:

// POST: api/Movies
public IHttpActionResult Post([FromBody]MovieModel movieModel)
{
    if (ModelState.IsValid)
    {
        //Code
    }
}

And a test method (is an integration test, but the same would happen in unit tests):

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

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

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

Despite the fact that the model is clearly invalid it always evaluates the IsValid property to true.

I tried many approaches so far without success.


Solution

  • 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());
    }