title: Unit Testing ASP.NET DataAnnotations validation
body: <p>I am using DataAnnotations for my model validation i.e.</p>
  <pre><code>[Required(ErrorMessage=&quot;Please enter a name&quot;)]
  public string Name { get; set; }
  </code></pre>
  <p>In my controller, I am checking the value of ModelState. This is correctly returning false for invalid model data posted from my view.</p>
  <p>However, when executing the unit test of my controller action, ModelState always returns true:</p>
  <pre><code>[TestMethod]
  public void Submitting_Empty_Shipping_Details_Displays_Default_View_With_Error()
  {
      // Arrange
      CartController controller = new CartController(null, null);
      Cart cart = new Cart();
      cart.AddItem(new Product(), 1);
  
      // Act
      var result = controller.CheckOut(cart, new ShippingDetails() { Name = &quot;&quot; });
  
      // Assert
      Assert.IsTrue(string.IsNullOrEmpty(result.ViewName));
      Assert.IsFalse(result.ViewData.ModelState.IsValid);
  }
  </code></pre>
  <p>Do I need to do anything extra to set up the model validation in my tests?</p>