2009-08-20 4 views
1

HttpRequest 준비 (래퍼 및 인터페이스) 준비가되었습니다 ... 생성자를 호출 할 필요가 없으므로이 메서드의 인터페이스를 중단하지 않고 가짜 HttpRequest를 전달하는 방법은 무엇입니까?종속성을 위조 개체로 사용하여 정적 메서드를 단위 테스트하는 방법?

public static int ParseQueryInt(string key, int defaultValue) 
{ 
    NameValueCollection nvc; 
    if (HttpContext.Current.Request.QueryString["name"] != null) 
    { 
     //Parse strings. 
    } 
} 

편집 :이 모든 상황에서 작동 할 가능성이 보면 나는 또한 스키트의 솔루션을 사용하지만 Akselson의 솔루션은, 놀랍게도 많은, 일을 가장 창조적이고 개념의 증거입니다.

public class Class1 
{ 
    [Test] 
    public void Test() 
    { 
     HttpContext.Current = new HttpContext(
new HttpRequest("test.aspx", "http://test.com/test.aspx", "querystring=value"), 
new HttpResponse(new StringWriter()) 
); 
     Assert.AreEqual(HttpContext.Current.Request.QueryString["querystring"], "value"); 
    } 
} 

답변

4

당신은 당신의 자신의 인스턴스에 HttpContext.Current를 설정할 수 있습니다

HttpContext.Current = new HttpContext(
    new HttpRequest("test.aspx","http://test.com/test.aspx","querystring=value"), 
    new HttpResponse(new StringWriter()) 
); 

당신이 테스트에서 그것을 가지고 전에 방법을 변경하지 않으려는 경우가 유용 할 수 있습니다.

7

하나의 옵션이 다른 과부하 소개입니다 :

public static int ParseQueryInt(string key, int defaultValue) 
{ 
    return ParseQuery(key, defaultValue, HttpContext.Current.Request); 
} 

public static int ParseQueryInt(string key, int defaultValue, 
           HttpRequest request) 
{ 
    NameValueCollection nvc; 
    if (request.QueryString["name"] != null) 
    { 
     //Parse strings. 
    } 
} 

그런 다음 간단한 리디렉션에 "검증 할"(또는 적어도 "하드 테스트하기") 코드를 줄일를 ... 당신은을 테스트 할 수 있습니다 요청을 받아들이는 버전에서 꺼내십시오.

+0

와우! 그리고 당신도 내 마음을 읽고 있었어 :) –

+6

두 번째 오버로드를 internal로 만들고 internalsVisibleTo 속성을 통해 테스트 어셈블리에서 사용할 수 있습니다. 따라서 단위 테스트 목적으로 API를 혼란스럽게하지 마십시오. –

관련 문제