title: ASP MVC 3 testing controller calling ModelState.IsValid always returns true
body: <p>I have an ASP MVC 3 application and in my Model I have implemented IValidatableObject.</p>
  
  <p>When my controller posts for a create or edit, I obviously only want to save the model if it is valid.</p>
  
  <p>I see many blogs and posts and answers that say something like</p>
  
  <pre><code>if(!ModelState.IsValid)
  {
        return View();
  }</code></pre>
  
  <p>My question.  Why is it that ModelState.IsValid is always true in a unit test on the Controller?</p>
  
  <p>Example:</p>
  
  <pre><code>[Test]
  public void InValidModelsAreNotAdded()
  {
      var invalidModel = new MyModel() { SomeField = "some data", SomeOtherField = "" };
  
      var result = _controller.Submit(invalidModel);
  
      _repository.AssertWasNotCalled(r => r.Add(Arg.Is.Anything));
  
  }</code></pre>
  
  <p>Model code:</p>
  
  <pre><code>
  public class MyModel : IValidatableObject
  {
      public string SomeField { get; set; }
      public string SomeOtherField { get; set; }
  
      public IEnumerable Validate(ValidationContext validationContext)
      {
          if(string.IsNullOrWhiteSpace(SomeOtherField))
          {
              yield return
                  new ValidationResult("Oops invalid.", new[] {"SomeOtherField"});
          }
       }
  }
  </code></pre>
  
  <p>The AssertWasNotCalled always fails this test.</p>
  
  <p>I stepped through the test and noticed that the ModelState.IsValid is true for this test.  It is as if the IValidatableObject.Validate is not being invoked.  It seems to work when I run the project, but thats not much of a way to test drive an application.</p>
  
  <p>Also, I realize I could use the <code>[Required]</code> attribute for my example, but my real code has much more complex validation to it.</p>
  
  <p>Thoughts?</p>