Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test Request.Form[""]?

Below is my controller's method :-

   [HttpPost]
   public ActionResult Search(SearchViewModel model)
   {
       string selection = Request.Form["Options"];
       if (selection == "str1")
       {
           -----------------------------
       }        
   }

And it's based on the condition where its getting value from Request.Form.But Request.Form is only provide Get property and i can't set it's value on unit testing method.Is there any way to set it's value ?

like image 809
Pawan Avatar asked Sep 04 '25 04:09

Pawan


2 Answers

None of the above methods work for me. I end up using the following without Mock.

DefaultHttpContext httpContext = new DefaultHttpContext();
httpContext.Request.Scheme = "http";
httpContext.Request.Host = new HostString("localhost");
var formCol = new FormCollection(new Dictionary<string, 
Microsoft.Extensions.Primitives.StringValues>
{   
            { "key1", "value1" },
            { "key2", "value2" }
}); 
httpContext.Request.ContentType = "application/x-www-form-urlencoded";
httpContext.Request.Form = formCol;
var context = new MyContext();
var controller = new MyController(context);
controller.ControllerContext = new ControllerContext {
            HttpContext = httpContext
};
like image 113
malach Avatar answered Sep 06 '25 04:09

malach


Do not use Request.Form["Options"] inside. You can have Option property inside your SearchViewModel class and can use it instead. For scenario where you are required to use session in the controller method you can use ModelBinder

like image 31
Rishikesh Avatar answered Sep 06 '25 04:09

Rishikesh