Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在尝试单元测试时触发初始化方法?_C#_Asp.net Mvc_Unit Testing_Moq - Fatal编程技术网

C# 如何在尝试单元测试时触发初始化方法?

C# 如何在尝试单元测试时触发初始化方法?,c#,asp.net-mvc,unit-testing,moq,C#,Asp.net Mvc,Unit Testing,Moq,我有下面的覆盖,可以使用FormSideEntity对象对Cookie执行一些操作。但是,当我在单元测试中实例化控制器时,不会触发此方法。有什么办法吗 protected override void Initialize(System.Web.Routing.RequestContext requestContext) { base.Initialize(requestContext); // Grab the user's login infor

我有下面的覆盖,可以使用FormSideEntity对象对Cookie执行一些操作。但是,当我在单元测试中实例化控制器时,不会触发此方法。有什么办法吗

   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)
的显式实现又可以调用它,因此此代码将初始化并执行控制器:

IController controller = new TestController();
controller.Execute(requestContext);
我已经分析了
Initialize()
的依赖关系树,我看不到任何其他不借助反射调用此方法的方法。您还需要创建传递给
Execute()
RequestContext
,这看起来更容易,因为您正在使用Moq:

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

有关于使用Moq模拟HttpContext的有用详细信息。

谢谢,Sam。我能够触发Initialize方法,但仍然会出错,模拟HttpContext比我想象的要困难得多。HttpContext是可测试性的反基督-我尽量远离它,我很惊讶Initialize()也是很弱的可测试性。也许您可以考虑使用自定义模型绑定器或属性依赖项注入,而不是使用Initialize()?