title: How do I test an ActionFilterAttribute with ASP.NET Web API?
body: <p>I'm building an ASP.NET Web API that uses a very simple action filter:</p>
  
  <pre><code>public class ValidateModelAttribute : ActionFilterAttribute {
      public override void OnActionExecuting(HttpActionContext actionContext) {
          if (actionContext.ModelState.IsValid == false) {
              var responseObject = new ApiResponse() {
                  Errors = actionContext.ModelState.Values.SelectMany(v =&gt; v.Errors).Select(e =&gt; e.ErrorMessage)
              };
  
              actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, responseObject);
          }
      }
  }
  </code></pre>
  
  <p>My action filter simply enforces that the <code>ModelState</code> is valid; if not, it returns a 400 with all the error messages so the client can do whatever they wish with the data.</p>
  
  <p>Here is how I'm using the attribute in my controller:</p>
  
  <pre><code>[ValidateModelAttribute]
  public HttpResponseMessage Db(DbModel model) {
      return Request.CreateResponse(HttpStatusCode.OK);
  }
  </code></pre>
  
  <p>I'm trying to test the attribute using Visual Studio's testing framework:</p>
  
  <pre><code>[TestMethod]
  public void CaptureApiDatabase_IfRequiredFieldMissing_ReturnHttpBadRequest() {
      var controller = new ConfigureController();
      controller.Request = new HttpRequestMessage();
      controller.Configuration = new HttpConfiguration();            
  
      var validationAttribute = new ValidateModelAttribute();
      validationAttribute.OnActionExecuting(controller.ActionContext);
      Assert.IsTrue(controller.ActionContext.Response.StatusCode == HttpStatusCode.BadRequest);
  }
  </code></pre>
  
  <p>This isn't working because I haven't provided the filter my data and as a result the <code>ModelState</code> is always valid.  How do I build a context so I can test this filter attribute?</p>