C# 为私有方法添加单元测试(反射)

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using System.Reflection;
   6:   
   7:  namespace TestProject
   8:  {
   9:      public class TestHelper
  10:      {
  11:          /// <summary>
  12:          /// 调用静态方法
  13:          /// </summary>
  14:          /// <param name="t">类全名</param>
  15:          /// <paramname="strMethod">方法名</param>
  16:          /// <paramname="aobjParams">参数表</param>
  17:          /// <returns>函数返回值</returns>
  18:          public static object RunStaticMethod(System.Type t, string strMethod, object[] aobjParams)
  19:          {
  20:              BindingFlags eFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
  21:              return RunMethod(t, strMethod, null, aobjParams, eFlags);
  22:          }
  23:   
  24:   
  25:          /// <summary>
  26:          /// 调用实例方法
  27:          /// </summary>
  28:          /// <param name="t">类全名</param>
  29:          /// <paramname="strMethod">方法名</param>
  30:          /// <paramname="objInstance">类的实例</param>
  31:          ///<paramname="aobjParams">参数表</param>
  32:          ///<returns>函数返回值</returns>
  33:          public static object RunInstanceMethod(System.Type t, string strMethod, object objInstance, object[] aobjParams)
  34:          {
  35:              BindingFlags eFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
  36:              return RunMethod(t, strMethod, objInstance, aobjParams, eFlags);
  37:          }
  38:   
  39:          private static object RunMethod(System.Type t, string strMethod, object objInstance, object[] aobjParams, BindingFlags eFlags)
  40:          {
  41:              MethodInfo m;
  42:              try
  43:              {
  44:                  m = t.GetMethod(strMethod, eFlags);
  45:                  if (m == null)
  46:                  {
  47:                      throw new ArgumentException("There is no method '" + strMethod + "' for type'" + t.ToString() + "'.");
  48:                  }
  49:                  object objRet = m.Invoke(objInstance, aobjParams);
  50:                  return objRet;
  51:              }
  52:              catch
  53:              {
  54:                  throw;
  55:              }
  56:          }
  57:      }
  58:  }
posted @ 2015-04-27 16:52 Ants 阅读(...) 评论(...) 编辑 收藏