教训:System.TypeInitializationException 类型初始值设定项引发异常

 



在单元测试中出现了这个异常,原因是:
由于在测试项目中没有添加配置文件(只有前台网站项目中添加了 web.config)

//通过配置文件获取连接字符串
public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.ConnectionStrings["MyPetShopConnection"].ConnectionString;

public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            int result = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return result;
        }

        /// <summary>
        /// 辅助函数
        /// </summary>
        /// <param name="cmd">命令对象</param>
        /// <param name="conn">连接对象</param>
        /// <param name="trans">事务对象</param>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">命令字符串</param>
        /// <param name="cmdParms">命令参数</param>
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {
            if(conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            cmd.CommandType = cmdType;

            if (trans != null)
                cmd.Transaction = trans;

            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }
// 解决方法:添加App.config
 <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="MyPetShopConnection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Web\MyPetShop\App_Data\MyPetShop.mdf;Integrated Security=True;User Instance=True"/>
  </connectionStrings>
</configuration>



教训:如果类中存在静态成员,应确保其初始化时不会抛出异常,否则会影响对该类的正常访问
另外可以参考文章:

通过七个关键编程技巧得益于静态内容
http://www.microsoft.com/china/MSDN/library/enterprisedevelopment/softwaredev/us0501StaticsinNET.mspx?mfr=true

内容转载于略作修改:http://www.cnblogs.com/simply-zhao/archive/2008/03/03/1088213.html

 

posted @ 2011-09-29 16:20  把爱延续  阅读(15095)  评论(1编辑  收藏  举报