gpt4 book ai didi

c# - 尝试单元测试时如何触发 Initialize 方法?

转载 作者:行者123 更新时间:2023-11-30 22:48:50 25 4
gpt4 key购买 nike

我有下面的重写来使用 FormsIdentity 对象对 cookie 做一些事情。但是当我在单元测试中实例化 Controller 时,不会触发此方法。任何想法如何做到这一点?

   protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);

// Grab the user's login information from FormsAuth
_userState = new UserState();
if (this.User.Identity != null && this.User.Identity is FormsIdentity)
this._userState.FromString(((FormsIdentity)this.User.Identity).Ticket.UserData);

// have to explicitly add this so Master can see untyped value
this.UserState = _userState;
//this.ViewData["ErrorDisplay"] = this.ErrorDisplay;

// custom views should also add these as properties
}

最佳答案

Controller.Initialize(RequestContext)ControllerBase.Execute(RequestContext) 中被调用,后者又可以被 IController.Execute 的显式实现调用(RequestContext),因此这段代码将初始化并执行一个 Controller :

IController controller = new TestController();
controller.Execute(requestContext);

我已经分析了 Initialize() 的依赖关系树,但我看不出有任何其他方式可以在不借助反射的情况下调用此方法。您还需要创建传递给 Execute()RequestContext,这更容易,因为看起来您正在使用 Moq:

var wrapper = new HttpContextWrapper(httpContext);
var requestContext = new RequestContext(wrapper, new RouteData());

This link包含有关使用 Moq 模拟 HttpContext 的有用详细信息。

关于c# - 尝试单元测试时如何触发 Initialize 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1452665/

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