Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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);
share|improve this question

2 Answers 2

up vote 4 down vote accepted

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|improve this answer
    
@Chris..Perfect buddy..Thank you :) Can you Please help me in mocking session too.? –  Sai Avinash Dec 5 '13 at 6:40
    
I might be able to help with that - what do you need to do? –  Chris Mantle Dec 9 '13 at 14:18
    
@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.. –  Sai Avinash Dec 9 '13 at 14:20

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.