title: test controller method + DataAnnotations - asp.net mvc 3
body: <p>This is a follow up on this:</p>
  
  <p><a href="https://stackoverflow.com/questions/6438527/unit-testing-controller">other SO post</a></p>
  
  <p>Is this a good way to test whether the validation based on DataAnnotations works in the controller: </p>
  
  <pre><code>[Test]
  public void UserController_CannotCreateUserWithNoLastName()
  {
      // Arrange
      var user = new CreateUserViewModel();
      UsersController controller = new UsersController();
      var validationContext = new ValidationContext(user, null, null);
      var validationResults = new System.Collections.Generic.List&lt;ValidationResult&gt;();
      Validator.TryValidateObject(user, validationContext, validationResults);
      foreach (var validationResult in validationResults)
      {
      controller.ModelState.AddModelError("", validationResult.ErrorMessage);
      }
  
      // Act
      var result = controller.CreateUser(user);
  
      // Assert
      Assert.IsFalse(controller.ModelState.IsValid);
  }
  </code></pre>
  
  <p>Any improvement suggestions would be very much welcome. I am also wondering whether one usually writes one test for each validation/business rule. Thanks!</p>