测试 private 方法需要使用反射
假设要测试下面 ClassLibrary1.Class1 中的 MyPrivateMethod() 方法:
using System; namespace ClassLibrary1 { /// <summary> /// Summary description for Class1. /// </summary> public class Class1 { protected int MyPrivateMethod(int val1, int val2) { return val1 + val2; } } // end of class } // end of namespace下面是测试类代码:using System; using System.Reflection; using NUnit.Framework; namespace ClassLibrary1 { /// <summary> /// Summary description for Tester. /// </summary> [TestFixture] public class Tester { [Test] public void MyPrivateMethod_Test() { ClassLibrary1.Class1 class1 = new ClassLibrary1.Class1(); object[] aobjParams = new object[] { 3, 4 }; object strRet; strRet = RunInstanceMethod(typeof(ClassLibrary1.Class1), "MyPrivateMethod", class1, aobjParams ); Assert.AreEqual(7, strRet.ToString()); } /// <summary> /// 运行静态方法 /// </summary> /// <param name="t"></param> /// <param name="strMethod"></param> /// <param name="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>