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的方法對我來說沒有意義。這只是一個額外的練習,需要編寫大量的代碼才能讀取和正確表達文件。
你同意我嗎?你在這種情況下做了什麼?