【问题标题】:Unit Test Controller with PerWebRequest LifeStyle dependency具有 PerWebRequest LifeStyle 依赖项的单元测试控制器
【发布时间】:2011-06-03 16:07:17
【问题描述】:

我正在尝试为依赖于生活方式为“PerWebRequest”的类型的控制器编写单元测试。

城堡抛出以下异常:

System.InvalidOperationException:HttpContext.Current 为空。 PerWebRequestLifestyle 只能在 ASP.Net 中使用。

我可以以某种方式模拟 HttpContext.Current 属性来解决这个问题吗?

我尝试使用 MVCContrib 的 TestControllerBuilder 来初始化这个控制器,但是没有任何效果。

  SymptomTopicController controller = new SymptomTopicController();
        controller.WorkOrderFulfillment = workOrderFulfillment;

        TestControllerBuilder controllerBuilder = new TestControllerBuilder();
        controllerBuilder.InitializeController(controller);

【问题讨论】:

    标签: asp.net-mvc httpcontext mvccontrib-testhelper


    【解决方案1】:

    你见过这个问题吗:Mock HttpContext.Current in Test Init Method

    【讨论】:

      【解决方案2】:

      抽象依赖,不要在测试中使用容器。

      【讨论】:

      • 依赖是抽象的。控制器依赖是通过注入来解决的。问题是如何模拟 HTTPContext 而不是如何编写单元测试。
      • 依赖显然没有抽象(够)。如果是,您将不需要在测试中使用 HTTPContext,因为控制器不会对它有任何硬依赖,并且按照您描述它的方式,它在您的情况下确实如此,这意味着它不是抽象的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 2016-07-24
      • 2016-05-03
      • 2014-08-01
      • 1970-01-01
      相关资源
      最近更新 更多