【问题标题】:Using the connectionstring in an nunit test在 nunit 测试中使用连接字符串
【发布时间】:2013-09-24 17:49:00
【问题描述】:

我们使用 nunit.exe 应用程序来运行我们的(集成)测试

现在我遇到了连接字符串没有从测试代码所在的 dll 中的 app.config 中获取的问题。

这听起来合乎逻辑,因为 nunit.exe 是启动应用程序而不是测试 dll(顺便说一下,当我从 Visual Studio 测试框架开始测试时它曾经工作过),但我应该将连接字符串放在 nunit 中吗? exe.config?

我尝试在测试代码中设置它们(适用于 appsettings:ConfigurationManager.AppSettings.Set("DownloadDirectory", mDir);),如下所示: ConfigurationManager.ConnectionStrings.Add(conset);(其中consetConnectionStringSettings 对象),但随后我收到连接字符串部分是只读的错误。

我应该怎么做才能在我的测试中使用连接字符串?

编辑: 我们使用实体框架,因此我们不能将连接字符串放在 appsettings 中,因为它直接从该部分读取,我找不到解决此问题的方法。

【问题讨论】:

    标签: c# .net unit-testing nunit


    【解决方案1】:

    使用反射,您可以(在内存中)更改 Configuration.ConnectionStrings[connectionName] 的值,在您的情况下,您可能会在 SetUp 或 TestFixtureSetUp 中执行此操作。见http://david.gardiner.net.au/2008/09/programmatically-setting.html

    // Back up the existing connection string
    ConnectionStringSettings connStringSettings = ConfigurationManager.ConnectionStrings[connectionName];
    string oldConnectionString = connStringSettings.ConnectionString;
    
    // Override the IsReadOnly method on the ConnectionStringsSection.
    // This is something of a hack, but will work as long as Microsoft doesn't change the
    // internals of the ConfigurationElement class.
    FieldInfo fi = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
    fi.SetValue(connStringSettings, false);
    
    // Set the new connection string value
    connStringSettings.ConnectionString = connectionStringNeededForNUnitTest;
    

    【讨论】:

    • 如果这是从 DLL 运行的,则不会有现有的连接字符串。在这种情况下,您需要添加一个新的连接字符串。
    【解决方案2】:

    我知道这不是您要寻找的答案,但它是我用来解决您同样问题的答案:

    至少在 EF5 和 EF4.3 中,您可以修改 DbContext 实现并添加一个接受硬编码连接字符串的构造函数,例如:

        public partial class MyContext : DbContext
        {
            public MyContext() : base("name=MyContext")
            {
            }
            // --- Here is the new thing:
            public MyContext(string entityConnectionString) : base(entityConnectionString)
            {
            }
            // --- New thing ends here
    
            // .... the rest of the dbcontext implementation follows below 
        } 
    

    每次重新生成上下文时,您都必须粘贴此内容,但恕我直言,这是值得的麻烦。连接字符串必须是使用元数据和所有内容格式化的实体框架,但您将能够弄清楚。只需将其保存在某个地方,以便您可以在需要时将其粘贴。

    【讨论】:

      【解决方案3】:

      您可以从 ConfigurationManager.AppSettings 读取连接字符串值,是的,它是只读的。您可以在 App.Config 中更改它。 如果您想更改连接字符串中的某些值,例如 URL,您可以在代码中更改您的 dataContext.URL 或任何您想要的编码属性。

      【讨论】:

      • 我们使用实体框架,所以我们不能将连接字符串放在 appsettings 中,因为它是从 部分读取的。
      【解决方案4】:

      我认为对于单元测试来说这可能很容易。您可以将连接字符串作为硬编码字符串直接放入测试类。在简单的单元测试中,您测试有限的逻辑范围,而不是真正关心输入参数

      【讨论】:

      • 我们使用实体框架,所以我们不能将连接字符串放在 appsettings 中,因为它是从 部分读取的
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多