zoukankan      html  css  js  c++  java
  • 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:  }
  • 相关阅读:
    【JAVA】空指针异常
    【JAVA】分隔字符串的小技巧
    【JAVA】imageio异常:不支持图像类型
    权限设计“终极”解决方案
    一直困扰我的.net 2.0和,net 1.1同时运行的问题解决了
    乱谈成本三
    SandBar学习笔记
    不是吧!怎么这样
    学习Java的相关知识
    代码自动生成工具的补充
  • 原文地址:https://www.cnblogs.com/leleroyn/p/4460646.html
Copyright © 2011-2022 走看看