2012-05-04 66 views
1

我已經能夠成功地通過跟隨hanselman文章和使用FakeHttpContext單元測試與上下文對象我的asp.net相關方法。nunit測試httpcontext對象爲asp.net的正確方法

我已被告知,構建FakeHttpContext如下,設置查詢字符串,裏面FakeHttpContext服務器變量如下是不是真正測試asp.net上下文對象。正如hanselman文章所提供的,這種方法和這個測試對我來說非常有效。

public static HttpContextBase FakeHttpContext() 
    { 
     var context = new Mock<HttpContextBase>(); 
     var request = new Mock<HttpRequestBase>(); 
     var response = new Mock<HttpResponseBase>(); 
     var session = new Mock<HttpSessionStateBase>(); 
     var server = new Mock<HttpServerUtilityBase>(); 

     request.Setup(x => x.QueryString).Returns(new NameValueCollection 
       { 
        {"blah","7"}, 
        {"blah1","8"} 
       }); 

     request.Setup(x => x.ServerVariables).Returns(new NameValueCollection 
       { 
        {"SERVER_NAME","myserver"}, {"SCRIPT_NAME","myperfectscript"}, 
        {"SERVER_PORT","80"}, {"HTTPS","www.microsoft.com"} 
       }); 

     request.Setup(x => x.Form).Returns(new NameValueCollection 
       { 
        {"TextBox1", "hello"}, 
        {"Button1", "world"}, 
        {"Label1", "yournamehere"} 
       }); 

     request.Setup(x => x.Cookies).Returns(new HttpCookieCollection()); 

     HttpCookie cookie1 = new HttpCookie("userInfo"); 
     cookie1["username"] = "Tom"; 
     cookie1["password"] = "pass"; 

     request.Object.Cookies.Add(cookie1); 

     HttpCookie cookie2 = new HttpCookie("compInfo"); 
     cookie2["companyname"] = "google"; 
     cookie2["companypassword"] = "googlepassword111"; 

     request.Object.Cookies.Add(cookie2); 

     context.Setup(ctx => ctx.Request).Returns(request.Object); 
     context.Setup(ctx => ctx.Response).Returns(response.Object); 
     context.Setup(ctx => ctx.Session).Returns(session.Object); 
     context.Setup(ctx => ctx.Server).Returns(server.Object); 

     return context.Object; 
    } 

有人告訴我捕捉到所有的頁面信息與通過提琴手一個文件中的所有響應/請求級別參數,文件讀入到測試對象,閱讀頁面級參數,例如從已保存的文件查詢字符串然後測試它。

這種使用file/fiddler的方法對我來說沒有意義。這只是一個額外的練習,需要編寫大量的代碼才能讀取和正確表達文件。

你同意我嗎?你在這種情況下做了什麼?

回答

1

我通常會聲明測試訪問像文件,數據庫,流等任何資源更集成測試比單元測試。如果您將這些測試作爲更大的持續集成環境的一部分運行,則這些測試可能會輕鬆失敗,並且僅因爲該文件被鎖定而出現紅色構建;例如...