2016-06-20 1 views
0

나는이 방법에 대한 단위 테스트를 구현하려고 할 때 이제 IP 주소HttpContext를 널이

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; 


     } 

을 평가하는 코드의 조각을 다음 한 항상 오류, Null 참조를 던졌습니다

HttpContext를가 아니기 때문에 나는 ...이 문제를 해결할 수있는 방법이 바로 단위 테스트에 대한 예상된다

감사

+0

당신이 [질문]에서보고있을 수 있습니다 (http://stackoverflow.com/questions/4379450/mock-httpcontext-current-in-test-init-method) ** httpContext **를 모의하는 방법을 보여줍니다. 나는 이것이 귀하의 상황에 좋은 해결책이 될 것이라고 생각합니다! –

답변

1

를 실제 방법을 변경할 수 단위 테스트 및 단위 테스트는 자체 컨텍스트에서 실행 가능합니다. 유닛 테스트에 HttpContext를 조롱하거나 제공하는 방법이 필요합니다.

+0

내가 누락 된 것이 아니라면, 실제 방법에서 변경이 필요하다. 나는 원하지 않는다. –

1

직접 "HttpContext.Current.Request.UserHostAddress"를 사용하지 않고 대신 wrapperclass 또는 기타 mockable 클래스를 사용하면 동작을 조롱 할 수 있습니다.

Here is an Example

당신은 아마 너무이 클래스의 테스트 독립을 얻을뿐만 아니라, System.Net.Dns.GetHostAddresses(strHostName).GetValue(0)을 조롱한다.

0

당신은 단위 테스트는 당신이 방법에 대한 다음 예에서와 같이 typemock을 사용할 수 있지만 HttpContext를 조롱하려는 경우 :

[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); 
} 
관련 문제