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

asp.net-mvc, c#, moq, request, unit-testing

Solution

`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);

Problem

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); ```

Original source