2

Possible Duplicate:
How do I mock the HttpContext in ASP.NET MVC using Moq?

One of my DLL's has a method like this

public void RegisterPerson(Person p,  HttpContext context)
{
    //extract Ip
    person.Ip=context.Request.UserHostAddress; 

    //Dome something Else
}

In My test i want to create a fake context and pass it to method, as Below

 [TestMethod]
  public void InsertPerson()
  { 
        Person p= new Person();
        _service.RegisterPerson(p, /*Fake context here*/);
  }

Please suggest me how to do this.

Community
  • 1
  • 1
Rusi Nova
  • 2,617
  • 6
  • 32
  • 48
  • Check this out: http://stackoverflow.com/questions/1452418/how-do-i-mock-the-httpcontext-in-asp-net-mvc-using-moq – Sam Nov 04 '11 at 15:22

2 Answers2

4

It is very hard to reasonably mock non *Base versions of the HttpContext and related classes. Consider switching your code to use *Base classes so you can actually mock them. You can easyly convert HttpContext to *Base version with HttpContextWrapper ( http://msdn.microsoft.com/en-us/library/system.web.httpcontextwrapper.aspx), but there is no built in way of doing reverse.

In your particular case consider passing in informaion that is really needed for the call (i.e. context.request.UserHostAddress) instead of whole HttpContext object.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
3

Generally methods are more testable if they ask for what they need instead of looking for what they need.

In your example that would mean passing in the relevant HttpContext properties (e.g. UserHostAddress) as parameters (asking for what you need, instead of looking inside an HttpContext). This may lead to methods that have more parameters, but they will be much more explicit and testable.

By making the RegisterPerson parameters explicit you don't need to guess which properties it will pull out of HttpContext (getting null references when you are wrong)--they are explicitly stated in the method's API. If you do anything wrong the compiler will let you know. If you need another property later simply add a parameter and the compiler will let you know everywhere you need to update.

See Google's guide to writing testable code for more information.

Kevin
  • 8,312
  • 4
  • 27
  • 31