【问题标题】:Unable to read configuration file in a test project无法读取测试项目中的配置文件
【发布时间】:2012-09-02 13:15:27
【问题描述】:

运行单元测试时,无法正确读取配置文件。 但是,当从控制台应用程序上下文运行时,会读取配置文件。

在下面的代码中,在赋值后访问var section时,运行测试TestIoCInit()时为null,从控制台应用程序调用InitIoC()时不为null .

    [TestMethod]
    public void TestIocInit()
    {
        InitIoC();
    }
    internal static void InitIoC()
    {
        IUnityContainer unityContainer = new UnityContainer(); // the host app domain creates the unity container and pass it to the resolver, the resolver is a static member of IoC class, thus the container is static

        ServiceLocator.SetLocatorProvider(unityContainer);

        var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
        section.Configure(unityContainer);

        var unityResolver = new UnityDependencyResolver(unityContainer);
        IoC.Initialize(unityResolver);
        new IoCTypeRegistrationTask(unityContainer).Execute();
    }

感谢您的帮助!

【问题讨论】:

    标签: c# unit-testing app-config


    【解决方案1】:

    您是否尝试在测试项目的 bin 目录中复制配置文件。 您应该将其重命名为

    Your_test_project_name.dll.config

    【讨论】:

      【解决方案2】:

      或者,您可以添加一个构建后步骤,将正在测试的项目的 app.config 复制到测试项目的目录中(首先将 app.config 添加到测试项目 - 它会被 app.config 覆盖来自被测项目)。这样,每次构建解决方案时,您都会获得一份复制到测试项目中的最新最好的 app.config 版本。

      【讨论】:

        【解决方案3】:

        您可以使用 ClassInit 将缺少的资源(配置文件、非托管程序集、数据文件)从测试的 source/bin 目录复制到测试结果输出目录。

        为此:

        1. 从 textContext.DeploymentDirectory 开始,向上遍历目录,直到到达解决方案的目录(使用目录名称,而不是完整路径,因此它可以在其他机器上运行)。

          1.1。如果你没有到达它(如果测试在构建服务器上运行),只上升到比“TestResults”高一个目录,然后进入子目录“Sources”。

        2. 使用相对于解决方案目录的路径计算测试项目的目录。

        3. 从项目目录或 bin 复制所需资源(如果从 bin 复制,请不要忘记检查配置和平台)。

        【讨论】:

          【解决方案4】:

          我最终添加了一个新的类库项目,并向其中添加了 [TestClass] 属性。 无需复制 app.config 文件即可完美运行。 谢谢。

          【讨论】:

            猜你喜欢
            • 2013-10-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-03-24
            • 1970-01-01
            相关资源
            最近更新 更多