8

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

2 Answers 2

12

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);
Sign up to request clarification or add additional context in comments.

3 Comments

@Chris..Perfect buddy..Thank you :) Can you Please help me in mocking session too.?
I might be able to help with that - what do you need to do?
@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..
0

Another alternative to mocking the Context and all it's dependencies is to abstract the entire context/Params collection in a separate class, and mock that instead. In many cases this will make it easier, and avoids having to mock a complicated object graph:

Ex:

public void MainMethod()
{
   var valueInQuestion = ISomeAbstraction.GetMyValue("FieldName");

}

You can now mock the GetMyValue method instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.