Unit tests on MVC validation

前端 未结 12 1220
离开以前
离开以前 2020-12-04 06:31

How can I test that my controller action is putting the correct errors in the ModelState when validating an entity, when I\'m using DataAnnotation validation in MVC 2 Previe

12条回答
  •  长情又很酷
    2020-12-04 07:00

    Hate to necro a old post, but I thought I'd add my own thoughts (since I just had this problem and ran across this post while seeking the answer).

    1. Don't test validation in your controller tests. Either you trust MVC's validation or write your own (i.e. don't test other's code, test your code)
    2. If you do want to test validation is doing what you expect, test it in your model tests (I do this for a couple of my more complex regex validations).

    What you really want to test here is that your controller does what you expect it to do when validation fails. That's your code, and your expectations. Testing it is easy once you realize that's all you want to test:

    [test]
    public void TestInvalidPostBehavior()
    {
        // arrange
        var mockRepository = new Mock();
        var homeController = new HomeController(mockRepository.Object);
        var p = new BlogPost();
    
        homeController.ViewData.ModelState.AddModelError("Key", "ErrorMessage"); // Values of these two strings don't matter.  
        // What I'm doing is setting up the situation: my controller is receiving an invalid model.
    
        // act
        var result = (ViewResult) homeController.Index(p);
    
        // assert
        result.ForView("Index")
        Assert.That(result.ViewData.Model, Is.EqualTo(p));
    }
    

提交回复
热议问题