[英]ASP.Net MVC 5 - Correct way to access HttpContext.Current.User outside of controller?
[英]Correct way to nunit test httpcontext object for asp.net
通过遵循hanselman文章并使用FakeHttpContext,我已经能够成功使用上下文对象对与asp.net相关的方法进行单元测试。
有人告诉我,如下构造FakeHttpContext并在FakeHttpContext内部设置QueryString和Server Variables 并不是对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;
}
我被告知要通过提琴手使用文件中的所有响应/请求级别参数捕获所有页面详细信息,将文件读入测试对象,从保存的文件中读取页面级别参数(例如查询字符串),然后对其进行测试。
这种使用文件/提琴手的方法对我来说没有意义。 这只是编写大量代码来读取和正则表达式的额外工作。
你是否同意我的观点? 在这种情况下,您做了什么?
我通常会声明访问文件,数据库,流等任何资源的测试,而不是单元测试。 如果您在较大的持续集成环境中运行这些测试,则这些测试很容易失败,并且由于文件被锁定等原因,您将获得红色版本...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.