gpt4 book ai didi

c# - 如何模拟 HttpContext 以访问 IIdentity 的扩展方法?

转载 作者:行者123 更新时间:2023-11-30 18:12:52 28 4
gpt4 key购买 nike

在我的 MVC 项目中,我正在为 Controller 构建单元测试以返回 View 。

这个controller的action结果构建了一个viewmodel,这个viewmodel的constructor调用

HttpContext.Current.User.Identity.NameWithoutDomain().ToUpper();

其中NameWithoutDomainIIdentity的扩展方法。

每当我运行它时,我总是收到“找不到对象”的消息,我很好奇如何适本地模拟它以进行单元测试?

扩展方法:

public static class SystemWebExtension
{
public static string NameWithoutDomain(this IIdentity identity)
{
return identity.Name.Split('\\').Last();
}
}

模型构造函数:

public Model()
{
this.PreparedByUser = HttpContext.Current.User.Identity.NameWithoutDomain().ToUpper();
this.AuthorizedBy = true;
this.AuthorizedByUser = HttpContext.Current.User.Identity.NameWithoutDomain().ToUpper();
this.IssueCredit = true;
this.CreateUser = string.IsNullOrEmpty(this.CreateUser) ? Environment.UserName.ToLower() : this.CreateUser;
this.CreateDate = this.CreateDate.HasValue ? this.CreateDate : DateTime.Now;
this.UpdateUser = string.IsNullOrEmpty(this.CreateUser) ? null : Environment.UserName.ToLower();
this.UpdateDate = this.CreateDate.HasValue ? DateTime.Now : (DateTime?) null;
}

最佳答案

避免与 HttpContext 耦合,因为它在单元测试时不可用。

您应该明确地将必要的值注入(inject)模型

public Model(IIdentity identity) {
this.PreparedByUser = identity.NameWithoutDomain().ToUpper();
this.AuthorizedBy = true;
this.AuthorizedByUser = identity.NameWithoutDomain().ToUpper();
this.IssueCredit = true;
this.CreateUser = string.IsNullOrEmpty(this.CreateUser) ? Environment.UserName.ToLower() : this.CreateUser;
this.CreateDate = this.CreateDate.HasValue ? this.CreateDate : DateTime.Now;
this.UpdateUser = string.IsNullOrEmpty(this.CreateUser) ? null : Environment.UserName.ToLower();
this.UpdateDate = this.CreateDate.HasValue ? DateTime.Now : (DateTime?) null;
}

由于使用了 Controller ,您可以访问其属性中的所需信息

//...

var model = new Model(this.User.Identity);

return View(model);

并且在测试时,您可以通过其 Controller 上下文配置 Controller

//...
var username = "some username here"
var identity = new GenericIdentity(username, "");
identity.AddClaim(new Claim(ClaimTypes.Name, username));
var principal = new GenericPrincipal(identity, roles: new string[] { });
var user = new ClaimsPrincipal(principal);

var context = new Mock<HttpContextBase>();
context.Setup(_ => _.User).Returns(user);

//...

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

关于c# - 如何模拟 HttpContext 以访问 IIdentity 的扩展方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54870385/

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