0

I have following piece of code to evaluate the IP address

 public string getIPAddress()
        {
            string IPAddress = string.Empty;
            String strHostName = HttpContext.Current.Request.UserHostAddress.ToString();
            IPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
            return IPAddress;


        }

Now when I tried to implement unit testing for this method, it always throws error, null reference,

I could not change the actual method just for unit testing, is there any way to handle this...

Thanks

Md. Parvez Alam
  • 4,326
  • 5
  • 48
  • 108
  • 1
    You may have a look at this [question](http://stackoverflow.com/questions/4379450/mock-httpcontext-current-in-test-init-method) which shows how to **mock a httpContext**. I think this would be a good solution in your situation! – Pilgerstorfer Franz Jun 20 '16 at 13:27

3 Answers3

1

That is expected because HttpContext is not available in unit tests and unit tests run in their own context. You will need to have a way to mock/provide HttpContext to your unit tests.

sam
  • 1,937
  • 1
  • 8
  • 14
1

if you would not use "HttpContext.Current.Request.UserHostAddress" direct - but through a wrapperclass or other mockable class instead, you could then mock the behaviour.

Here is an Example

you should probably mock System.Net.Dns.GetHostAddresses(strHostName).GetValue(0) as well, to get your Test independent of this Class too.

neer
  • 4,031
  • 6
  • 20
  • 34
Tom Söhne
  • 512
  • 2
  • 6
0

if you want to mock HTTPContext while unit testing you can use typemock as in the following example regarding you method:

[TestMethod,Isolated]
public void TestForHttpContext_willReturn123AsIP()
{
    // Arrange
    Program classUnderTest = new Program();
    IPAddress[] a = { new IPAddress(long.Parse("123")), new IPAddress(long.Parse("456")), new IPAddress(long.Parse("789")) };

    Isolate.WhenCalled(() => HttpContext.Current.Request.UserHostAddress).WillReturn("testIP");
    Isolate.WhenCalled(() => Dns.GetHostAddresses(" ")).WillReturn(a);

    // Act
    var res = classUnderTest.getIPAddress();

    // Assert
    Assert.AreEqual("123.0.0.0", res);
}
JamesR
  • 745
  • 4
  • 15