当前位置 : 主页 > 编程语言 > c语言 >

c# 单元测试 ,对静态方法(static)和私有方法(private) 进行单元测试

来源:互联网 收集:自由互联 发布时间:2021-06-25
利用反射: /// summary /// 调用静态方法 /// /summaryakf /// param name="t"类全名/param /// paramname="strMethod"方法名/param /// paramname="aobjParams"参数表/param /// returns函数返回值/returns public static object

利用反射:

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

}

网友评论