0

I've written two extension methods for getting IP / Browser from current HttpRequest:

public static class Extensions
{    
    public static string IP (this HttpRequest currentRequest)
    {
        string ips = currentRequest.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (!string.IsNullOrEmpty(ips))
        {
            return ips.Split(',')[0];
        }
        return currentRequest.ServerVariables["REMOTE_ADDR"];
    }

    public static string Browser (this HttpRequest currentRequest)
    {
        return currentRequest.Browser.Type;
    }
}

I would like to unit test both methods. I've seen answers how to mock http request like this and this. But I can not mock IP and Browser from HttpRequest. Any ideas ?

Community
  • 1
  • 1
FrenkyB
  • 5,161
  • 8
  • 54
  • 91
  • How about first mocking HttpRequest, and then just request.ServerVariables["HTTP_X_FORWARDED_FOR"] = "fake ip"? But in general, don't use static methods if you want this part of functionality to be testable with unit tests. – Evk Oct 02 '16 at 13:23
  • 2
    Given that all dependencies are passed in and no dependency is made on other static classes, this is still nice and testable. – jessehouwing Oct 02 '16 at 13:25
  • @Evk - I've tried your solution and it doesn't work. – FrenkyB Oct 02 '16 at 13:32
  • Doesn't work how exactly? – Evk Oct 02 '16 at 13:36
  • The exception is thrown: System.PlatformNotSupportedException - Operation is not supported on this platform. It is thrown immediately after sentence: request.ServerVariables["HTTP_X_FORWARDED_FOR"] = "fake ip" – FrenkyB Oct 02 '16 at 13:37

0 Answers0