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

11,471

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);
Share:
11,471

Related videos on Youtube

Sai Avinash
Author by

Sai Avinash

Interested in all Microsoft technology stack

Updated on June 25, 2022

Comments

  • Sai Avinash
    Sai Avinash about 2 years

    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);
    
  • Sai Avinash
    Sai Avinash over 10 years
    @Chris..Perfect buddy..Thank you :) Can you Please help me in mocking session too.?
  • Chris Mantle
    Chris Mantle over 10 years
    I might be able to help with that - what do you need to do?
  • Sai Avinash
    Sai Avinash over 10 years
    @Chris..Thanks for response..I need to setup some session variables since the method that uses makes use of session variables which i should be mocking .. For eaxmple : Session["UserName"]="Avinash" some thing like that..