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

时间:2016-07-08 13:10:18

标签: c# unit-testing visual-studio-2015

我正在尝试从另一个项目访问一个类函数到visual studio中的单元测试项目。但它在运行时显示异常: -

  

[System.TypeInitializationException] = {System.TypeInitializationException:'MyDoc.Insert'的类型初始值设定项引发异常。 ---> System.NullReferenceException:未将对象引用设置为对象的实例。

我的代码如下:

SqlTransaction transaction;
SqlConnection con = new SqlConnection(dbConnString);
con.Open();
transaction = con.BeginTransaction();
Insert insobj = new Insert();**Exception generate here when creating insert class object** 
rowid = insobj.AffiliationInsert("SP_AFFILIATIONS", "testaff", con, transaction);
Assert.AreEqual(54, rowid);

catch (Exception ex) {
    throw ex;
}

请建议我如何解决这个问题。

Insert.CS

 public class Insert
    {
       SqlDataReader dr;
        private static string dbConnString = ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString;
        public string AffiliationInsert(string SP_AFFILIATIONS, string p_AffiliationName, SqlConnection con, SqlTransaction transaction)
        {
            try
            {
                //using (SqlConnection con = new SqlConnection(dbConnString))
                //{
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandText = SP_AFFILIATIONS;
                cmd.Transaction = transaction;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@affilationname", SqlDbType.VarChar).Value = p_AffiliationName;
                // con.Open();
                dr = cmd.ExecuteReader();
                string rowid = "";
                while (dr.Read())
                {
                    rowid = dr[0].ToString();
                }
                dr.Close();
                dr.Dispose();
                return rowid;
                //    con.Close();
                //}
            }

            catch
            {
                throw;
            }
            finally
            {

            }
        }
}

0 个答案:

没有答案