Scott Hanselman 的页面上有一些印刷错误(小写的类名)。所以这就是代码的样子(我还Expect
用新语法改变了旧Setup
语法):
public static class MvcMockHelpers
{
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>();
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;
}
}
回到你的情况。您会看到此异常,因为在创建假 HttpContext 时,仅设置了其直接属性 Request、Response、Session 和 Server。但是您正在尝试访问ServerVariables
请求模拟的属性。因此,您需要为此属性设置一些返回结果。请参阅 Scott 如何为请求模拟设置请求 url 的示例:
public static void SetupRequestUrl(this HttpRequestBase request, string url)
{
if (url == null)
throw new ArgumentNullException("url");
var mock = Mock.Get(request);
mock.Setup(req => req.QueryString)
.Returns(GetQueryStringParameters(url));
mock.Setup(req => req.AppRelativeCurrentExecutionFilePath)
.Returns(GetUrlFileName(url));
mock.Setup(req => req.PathInfo)
.Returns(string.Empty);
}
这里的主要思想 - 你不能直接使用contextBase.Request.QueryString
你应该在之前设置请求模拟:
mock.Setup(req => req.QueryString)
.Returns(GetQueryStringParameters(url));