2009-08-20 7 views
1

私はHttpRequestの準備ができています(ラッパーとインターフェイス)...コンストラクタを呼び出す必要はないので、このメソッドのインターフェイスを壊さずに、偽のHttpRequestをどのように渡しますか?依存関係のために偽のオブジェクトを使って静的メソッドをユニットテストする方法は?

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

EDIT: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

2番目のオーバーロードをinternalにして、internalsVisibleTo属性を使ってテストアセンブリから使用することができます。したがって、単体テストの目的でAPIを混乱させることはありません。 –

関連する問題