c# 單元測試 ,對靜態方法(static)和私有方法(private) 進行單元測試


利用反射:

 /// <summary>
        /// 調用靜態方法
        /// </summary>akf
        /// <param name="t">類全名</param>

        /// <paramname="strMethod">方法名</param>

        /// <paramname="aobjParams">參數表</param>

        /// <returns>函數返回值</returns>

        public static object RunStaticMethod(System.Type t, string strMethod, object[] aobjParams)
        {

            BindingFlags eFlags =

            BindingFlags.Static | BindingFlags.Public |

             BindingFlags.NonPublic;

            return RunMethod(t, strMethod,

             null, aobjParams, eFlags);

        }

        /// <summary>

        /// 調用實例方法

        /// </summary>

        /// <param name="t">類全名</param>

        /// <paramname="strMethod">方法名</param>

        /// <paramname="objInstance">類的實例</param>

        ///<paramname="aobjParams">參數表</param>

        ///<returns>函數返回值</returns>



        public static object RunInstanceMethod(System.Type t, string strMethod,

         object objInstance, object[] aobjParams)
        {

            BindingFlags eFlags = BindingFlags.Instance | BindingFlags.Public |

             BindingFlags.NonPublic;

            return RunMethod(t, strMethod,

             objInstance, aobjParams, eFlags);

        }



        private static object RunMethod(System.Type t, string

         strMethod, object objInstance, object[] aobjParams, BindingFlags eFlags)
        {

            MethodInfo m;

            try
            {

                m = t.GetMethod(strMethod, eFlags);

                if (m == null)
                {

                    throw new ArgumentException("There is no method '" +

                     strMethod + "' for type'" + t.ToString() + "'.");

                }

                object objRet = m.Invoke(objInstance, aobjParams);

                return objRet;

            }

            catch
            {

                throw;

            }

        }

  

在測試的時候例子:

假如在windows form1中有2個方法,分別是一個靜態方法和一個私有實例方法如下:

private static string StaticMethod(string s, int i)
        {


            return  s+i;
        
        }


        private string InstanceMethod(string s, int i)
        {


            return s + i;

        }

  

 

測試代碼可以這樣調用:

 

[TestMethod]
public void TestInstanceMethod()
{

Form1 f = new Form1();
//f.msg(f);
//f.button1_Click(null, null);

string ret = "" + RunInstanceMethod(typeof(Form1), "InstanceMethod", f, new object[] { "123", 123 });

Assert.AreEqual(ret, "123123");

}


[TestMethod]
public void TestStaticMethod()
{

string ret = "" + RunStaticMethod(typeof(Form1), "StaticMethod", new object[] { "123", 123 });

Assert.AreEqual(ret, "123123");


}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM