在单元测试中使用MVC4模拟HttpContext不起作用

时间:2014-03-03 11:04:16

标签: unit-testing asp.net-mvc-4 mocking moq httpcontext

我正在尝试使用moq来模拟HttpContext。我使用以下代码(使用https://gist.github.com/frankshearar/837741):

public HttpContextBase FakeHttpContext()
{
    var browser = new Mock<HttpBrowserCapabilitiesBase>(MockBehavior.Strict);
    var context = new Mock<HttpContextBase>(MockBehavior.Strict);
    var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
    var response = new Mock<HttpResponseBase>(MockBehavior.Strict);
    var session = new Mock<HttpSessionStateBase>(MockBehavior.Strict);
    var server = new Mock<HttpServerUtilityBase>(MockBehavior.Strict);
    var files = new Mock<HttpFileCollectionBase>(MockBehavior.Strict);
    var user = new Mock<IPrincipal>(MockBehavior.Strict);
    var identity = new Mock<IIdentity>(MockBehavior.Strict);
    var cookies = new HttpCookieCollection();
    var items = new ListDictionary();

    browser.Setup(b => b.IsMobileDevice).Returns(false);

    request.Setup(r => r.Cookies).Returns(cookies);
    request.Setup(r => r.ValidateInput());
    request.Setup(r => r.UserAgent).Returns("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11");
    request.Setup(r => r.Browser).Returns(browser.Object);
    request.Setup(req => req.ApplicationPath).Returns("~/");
    request.Setup(req => req.AppRelativeCurrentExecutionFilePath).Returns("~/");
    request.Setup(req => req.PathInfo).Returns(string.Empty);
    request.Setup(req => req.Form).Returns(new NameValueCollection());
    request.Setup(req => req.QueryString).Returns(new NameValueCollection());
    request.Setup(req => req.Files).Returns(files.Object);

    response.Setup(res => res.ApplyAppPathModifier(It.IsAny<string>())).
        Returns((string virtualPath) => virtualPath);

    user.Setup(usr => usr.Identity).Returns(identity.Object);

    identity.SetupGet(ident => ident.IsAuthenticated).Returns(true);

    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);
    context.Setup(ctx => ctx.User).Returns(user.Object);
    context.Setup(ctx => ctx.Items).Returns(items);

    return context.Object;
}

并设置控制器上下文:

var context = FakeHttpContext();

EmailContentController controller = kernel.Get<EmailContentController>();

controller.ControllerContext = new ControllerContext(context, new RouteData(), controller);

但是,当尝试访问控制器上下文(或任何其他模拟对象,如请求)时,我收到一个System.ArguementException并显示以下消息:

无法在对象实例上找到该方法。

知道造成什么原因吗?还有其他方法我错过了,需要嘲笑吗?

当我实现ControllerContext时会发生错误,因此看起来它看起来像是没有被模拟的东西。

谢谢!

0 个答案:

没有答案