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 @   Ants  阅读(1318)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
点击右上角即可分享
微信分享提示