再贴一个用于在单元测试中访问非public成员的TestHelper(原作者:hbifts),主要用于测试GUI代码。你能猜出我这么说的理由吗?
public class TestHelper
{
public static object Create(string assemblyName, string typeName, object[] args)
{
Assembly asm = Assembly.Load(assemblyName);
Type typeToCreate = asm.GetType(typeName,true,true);
return Activator.CreateInstance(typeToCreate,args,null);
}
public static object InvokeMethod(object obj,string methodName,object[] args)
{
Type objType = obj.GetType();
Type[] argTypes = new Type[args.Length];
for(int i=0;i<args.Length;i++)
{
argTypes[i] = args[i].GetType();
}
MethodInfo method = objType.GetMethod(methodName,BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,null,argTypes,null);
return method.Invoke(obj,args);
}
public static object GetField(object obj, string fieldName)
{
Type objType = obj.GetType();
FieldInfo fieldInfo = objType.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
return fieldInfo.GetValue(obj);
}
}
{
public static object Create(string assemblyName, string typeName, object[] args)
{
Assembly asm = Assembly.Load(assemblyName);
Type typeToCreate = asm.GetType(typeName,true,true);
return Activator.CreateInstance(typeToCreate,args,null);
}
public static object InvokeMethod(object obj,string methodName,object[] args)
{
Type objType = obj.GetType();
Type[] argTypes = new Type[args.Length];
for(int i=0;i<args.Length;i++)
{
argTypes[i] = args[i].GetType();
}
MethodInfo method = objType.GetMethod(methodName,BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,null,argTypes,null);
return method.Invoke(obj,args);
}
public static object GetField(object obj, string fieldName)
{
Type objType = obj.GetType();
FieldInfo fieldInfo = objType.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
return fieldInfo.GetValue(obj);
}
}