c# - 在测试初始化​​方法中模拟 HttpContext.Current

标签 c# unit-testing mocking httpcontext

我正在尝试将单元测试添加到我构建的 ASP.NET MVC 应用程序中。在我的单元测试中,我使用以下代码:

[TestMethod]
public void IndexAction_Should_Return_View() {
    var controller = new MembershipController();
    controller.SetFakeControllerContext("TestUser");

    ...
}

使用以下助手来模拟 Controller 上下文:

public static class FakeControllerContext {
    public static HttpContextBase FakeHttpContext(string username) {
        var context = new Mock<HttpContextBase>();

        context.SetupGet(ctx => ctx.Request.IsAuthenticated).Returns(!string.IsNullOrEmpty(username));

        if (!string.IsNullOrEmpty(username))
            context.SetupGet(ctx => ctx.User.Identity).Returns(FakeIdentity.CreateIdentity(username));

        return context.Object;
    }

    public static void SetFakeControllerContext(this Controller controller, string username = null) {
        var httpContext = FakeHttpContext(username);
        var context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
        controller.ControllerContext = context;
    }
}

此测试类继承自具有以下内容的基类:

[TestInitialize]
public void Init() {
    ...
}

在这个方法中,它调用了一个库(我无法控制),它试图运行以下代码:

HttpContext.Current.User.Identity.IsAuthenticated

现在您大概可以看出问题所在了。我已经针对 Controller 设置了假的 HttpContext,但没有在这个基本的 Init 方法中设置。单元测试/模拟对我来说很新,所以我想确保我做对了。我模拟 HttpContext 的正确方法是什么,以便它在我的 Controller 和我的 Init 方法中调用的任何库之间共享。

最佳答案

HttpContext.Current 返回 System.Web.HttpContext 的一个实例,不扩展 System.Web.HttpContextBase . HttpContextBase 是后来添加的,以解决 HttpContext 难以模拟的问题。这两个类基本上无关(HttpContextWrapper 用作它们之间的适配器)。

幸运的是,HttpContext 本身是可伪造的,足以让您替换 IPrincipal(用户)和 IIdentity

以下代码按预期运行,即使在控制台应用程序中也是如此:

HttpContext.Current = new HttpContext(
    new HttpRequest("", "http://tempuri.org", ""),
    new HttpResponse(new StringWriter())
    );

// User is logged in
HttpContext.Current.User = new GenericPrincipal(
    new GenericIdentity("username"),
    new string[0]
    );

// User is logged out
HttpContext.Current.User = new GenericPrincipal(
    new GenericIdentity(String.Empty),
    new string[0]
    );

关于c# - 在测试初始化​​方法中模拟 HttpContext.Current,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4379450/

相关文章:

c++ - 在 Catch2 中指定外部文本文件路径的最佳方式

Selenium/Ubuntu 的 PHPUnit fatal error

testing - 为非 GORM 对象构建 Grails 测试数据

javascript - 如何在单元测试期间验证已调用某个javascript函数

c# - 从 watch 或即时窗口打破无限循环

c# - 如何在 C# 中使用 FileOpen (VB.NET)?

c# - 为什么不能在 Page.PreInit 事件之后动态应用主题和母版页?

scala - 检查 Scala 中两个 Spark DataFrame 的相等性

c# - TDD:.NET 遵循 TDD 原则,模拟/不模拟?

c# - Jagged array 和 flatten array,哪个性能更好?