Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Mock Request object in unit testing asp.net mvc application

I am working on an asp.net mvc 3.0 application. In unit testing one of the action method in my controller, I was getting an error.

How to mock: Request.Params["FieldName"]

I have included Moq framework, but was not sure how to pass value

Here is my code... Please suggest...

 var request = new Mock<System.Web.HttpRequestBase>();

 request
     .SetupGet(x => x.Headers)
     .Returns(
         new System.Net.WebHeaderCollection
         {
             {"X-Requested-With", "XMLHttpRequest"}
         });

 var context = new Mock<System.Web.HttpContextBase>();

 context.SetupGet(x => x.Request).Returns(request.Object);

 ValidCodeController target = new ValidCodeController();

 target.ControllerContext =
     new ControllerContext(context.Object, new RouteData(), target);
like image 400
Sai Avinash Avatar asked Dec 04 '13 14:12

Sai Avinash


1 Answers

Params is a NameValueCollection property that can be set-up in a similar way to Headers:

var requestParams = new NameValueCollection
{
    { "FieldName", "value"}
};

request.SetupGet(x => x.Params).Returns(requestParams);
like image 132
Chris Mantle Avatar answered Nov 01 '22 13:11

Chris Mantle