Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelState.IsValid does not validate model

My Model class is as follow :

public class PostInputViewModel
    {
        [Required]
        [MinLength(1)]
        [MaxLength(125)]
        public string Title { get; set; }

        [Required]
        [AllowHtml]
        [Display(Name="Content")]
        public string Content { get; set; }
    }

and controller is as follow :

[HttpPost]
        public ActionResult Write(PostInputViewModel input)
        {
            if (!ModelState.IsValid)
                return View(input);

            var post = new Post
            {
                Title = input.Title,
                Content = input.Content,
                DateCreated = DateTime.Now,
                DateModified = DateTime.MaxValue,
            };

            dbContext.Posts.Add(post);
            dbContext.SaveChanges();

            return RedirectToAction("Index", "Home");
        }

When I run web application by clicking F5, and if I don't input title and content value, ModelState.IsValid is false, However if I test controller class with unit test case, ModelState.IsValid is always true. The test case is as follow :

[TestMethod]
        public void write_should_validate_model()
        {
            var input = new PostInputViewModel();
            input.Title = null;
            input.Content = null;
            var actionResult = controller.Write(input) as ViewResult;

            Assert.IsFalse(actionResult.ViewData.ModelState.IsValid);
        }

Am I missing something? Thanks in advance.

like image 704
Ray Avatar asked Jul 28 '26 04:07

Ray


1 Answers

If you want to have your controller try to validate the model, you can call the TryValidateModel method before your assert:

controller.TryValidateModel(input);

But I agree that you'd really only be testing the validation attributes. It might be OK, though; it would validate that your model has the expected attributes applied.

like image 102
Jacob Avatar answered Jul 29 '26 17:07

Jacob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!