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");


}

 

上一篇:如何利用Python实现自动打卡签到


下一篇:C# 一些代码小结--UI操作