C# Visual Studio Unit Test, Mocking up a client IP address
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 开发者_Go百科address without rewriting my code to accept IP address as a parameter?
Thanks!
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 :-)
精彩评论