通过遵循hanselman文章并使用 FakeHttpContext,我已经能够成功地使用上下文对象对我的 asp.net 相关方法进行单元测试。
有人告诉我,如下构造 FakeHttpContext 并在 FakeHttpContext 中设置 QueryString、服务器变量如下所示并不是对 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;
}
我被告知通过 fiddler 捕获文件中所有响应/请求级别参数的所有页面详细信息,将文件读入测试对象,从保存的文件中读取页面级别参数(例如查询字符串),然后对其进行测试。
这种使用文件/提琴手的方法对我来说没有意义。这只是编写大量代码来读取和正则表达式文件的额外练习。
你是否同意我的观点?在这种情况下你做了什么?