title: How to Test a C# WebApi post method that receive a FormData
body: <p>I have a controller with a post method:</p>
  
  <pre><code>public HttpResponseMessage Post()
          {            
              System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
              var name = System.Web.HttpContext.Current.Request.Form.Get("Name");
              var description = System.Web.HttpContext.Current.Request.Form.Get("Description");
              HttpPostedFile theFile = null;
              if (files.Count &gt; 0)
              {
                  theFile = files[0];
              }
              var categoryPost = new CategoryPostDto()
              {
                  Id = 1,
                  Name = name,
                  Description = description,
                  Logo = theFile
              };
              //var categoryService = new CategoryServiceFake();
              try
              {
                  //var newCategory = categoryService.AddCategory(name, description, files);
                  var newCategory = categoryService.AddCategory(categoryPost);
                  return Request.CreateResponse(HttpStatusCode.OK, newCategory);
              }
              catch (Exception ex)
              {
                  return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
              }
          }
  </code></pre>
  
  <p>On this controller I receive a formData from the front end, it works but i want to do the unitesting I tried to generate the context based on this post:</p>
  
  <p><a href="https://stackoverflow.com/questions/20747615/unit-test-asp-net-web-api-controller-with-fake-httpcontext">Unitesting a post method</a></p>
  
  <p>I did this implementation on my unit test but it doesn't work:</p>
  
  <pre><code>[TestMethod]
          public void TestMethod1()
          {
              //arrange
              var formData = new NameValueCollection { { "Name", "Hotels" } };
              var request = new Mock&lt;HttpRequestBase&gt;();
              request.SetupGet(r =&gt; r.Form).Returns(formData);
              var context = new Mock&lt;HttpContextBase&gt;();
              context.SetupGet(c =&gt; c.Request).Returns(request.Object);
  
              var myController = new CategoriesController();
              myController.Request = new HttpRequestMessage();
              myController.Configuration = new HttpConfiguration();
              myController.ControllerContext = new ControllerContext(context.Object, new RouteData(), myController);
              //act
              var response = myController.Post();
  
              CategoryPostDto categoryPostDto;
              Assert.IsTrue(response.TryGetContentValue&lt;CategoryPostDto&gt;(out categoryPostDto));
              Assert.AreEqual("Hotels", categoryPostDto.Name);            
          }
  </code></pre>