mardi 31 mai 2016

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

I have tried to make this works 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 evaluate the IsValid property to true.

I tried many approaches so far without success.

Aucun commentaire:

Enregistrer un commentaire