gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:30:41 25 4
gpt4 key购买 nike

我正在尝试将单元测试添加到我构建的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com