views:

136

answers:

1

Hey guys,

I am writing some unit tests and I'm getting an exception thrown from my real code when trying to do the following:

string IPaddress = HttpContext.Current.Request.UserHostName.ToString();

Is there a way to mock up an IP address without rewriting my code to accept IP address as a parameter?

Thanks!

+1  A: 

Take a look at Dependency Injection.

Basically you get around such issues by pushing the data into a class with (for example in this case) a "context" or "settings" class.

public interface IAppContext
{
  string GetIP();
}

You then have a prod implementation that does the real thing and a mock or fake in you tests.

public class AppContext : IAppConext
{
  public string GetIP()
  {
    return HttpContext.Current.Request.UserHostName.ToString();
  }
}

The app context gets pushed into the class using the ip address...

Oh- and as far as I know there is no inbuilt mocking for any VS editions, you will need to check out one of the many - Rhino mocks, Moq... there are many! Also see typemock but it takes a different approach.

PK :-)

Paul Kohler
Yeah I know about dependency injection, I just wanted to avoid having to change my existing code :(
Jimmy
There is Type mock - http://site.typemock.com/ - but I have never used it, I have always had the time to change the code! ;-)
Paul Kohler