我如何对我的控制器进行单元测试,以确保Windsor在使用PerWebRequest Lifestyle时能够解析依赖关系

时间:2011-04-24 18:49:36

标签: c# unit-testing castle-windsor

我的申请中有以下单元测试:

    [TestMethod]
    public void Windsor_Can_Resolve_HomeController_Dependencies()
    {
        // Setup
        WindsorContainer container = new WindsorContainer();
        container.Install(FromAssembly.Containing<HomeController>());

        // Act
        container.Kernel.Resolve(typeof(HomeController));
    }

这一点是为了确保我没有任何windsor配置问题,在我访问该控制器上的操作之前我将无法实现。问题是我的所有对象注册都注册为PerWebRequestLifestyle所以我不会遇到我的实体框架数据上下文在Web请求之间共享的问题(这会在运行多个操作时导致错误)。

但是,每当我运行此单元测试时,我都会遇到以下异常:

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

如何在不改变对象注册命令的生活方式的情况下测试此场景?

1 个答案:

答案 0 :(得分:18)

我不知道你是否可以在ASP.NET(MVC)之外使用PerWebRequestLifestyle(我认为你不能),但你可以使用IContributeComponentModelConstruction to modify the lifestyle of the components when they are registered

这将使您能够(集成)测试容器,而无需修改任何安装程序。