【问题标题】:C# why unit test has this strange behaviour?C# 为什么单元测试有这种奇怪的行为?
【发布时间】:2010-06-10 15:09:21
【问题描述】:

我有一个类来加密连接字符串。

    public class SKM
        {
            private string connStrName = "AndeDBEntities";

        internal void encryptConnStr()
        {
            if(isConnStrEncrypted())
                return;
            ...
        }

        private bool isConnStrEncrypted()
        {
            bool status = false;
            // Open app.config of executable.
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            // Get the connection string from the app.config file.
            string connStr = config.ConnectionStrings.ConnectionStrings[connStrName].ConnectionString;

            status = !(connStr.Contains("provider"));
            Log.logItem(LogType.DebugDevelopment, "isConnStrEncrypted", "SKM::isConnStrEncrypted()", "isConnStrEncrypted=" + status);
            return status;

        } 

   }

以上代码在我的应用程序中运行良好。但不在我的单元测试项目中。

在我的单元测试项目中,我测试了encryptConnStr() 方法。它将调用isConnStrEncrypted() 方法。然后在这一行会抛出异常(空指针):

string connStr = config.ConnectionStrings.ConnectionStrings[connStrName].ConnectionString;

我必须使用这样的索引才能通过单元测试:

string connStr = config.ConnectionStrings.ConnectionStrings[0].ConnectionString;

我记得几天前我在上面添加单元测试时它工作了。但现在它给了我一个错误。单元测试尚未与我们的日常自动构建集成。我们只有一个 connectionStr。它适用于产品,但不适用于单元测试。不知道为什么。谁能给我解释一下?

【问题讨论】:

    标签: c# unit-testing


    【解决方案1】:

    单元测试项目使用自己的配置文件。该文件中是否也存在连接字符串?

    【讨论】:

      【解决方案2】:

      config.ConnectionStrings 通常会尝试读取执行此代码的进程的 app/web.config 文件。因此,您可能需要在单元测试项目中添加一个包含连接字符串的 app.config 文件。

      【讨论】:

        【解决方案3】:

        我个人建议将您的加密测试方法分离为更通用的 IsStringEncrypted。

        这样您就可以测试加密方法,而不必担心数据库、连接字符串或 web/app.configs。

        在您的代码中,您只需调用

        字符串连接字符串 = GetConnectionStringFromAppConfig(); SKM.IsStringEncrypted(connectionString);

        在您的单元测试中,您只需定义该特定测试的连接字符串。

        【讨论】:

          猜你喜欢
          • 2015-08-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-27
          • 1970-01-01
          • 1970-01-01
          • 2018-06-29
          相关资源
          最近更新 更多