PrivateObject in Visual Studio

前端 未结 1 961
梦如初夏
梦如初夏 2021-01-28 02:10

I am using Visual Studio 2019 and in an MSTest Test Project (.NET Core) I am trying to use PrivateObject to test a protected method.

For example, I\'m tryin

相关标签:
1条回答
  • 2021-01-28 02:27

    I think PrivateObject does not exist in .Net Core. You can use these extensions to invoke non public members.

    public static T CallNonPublicMethod<T>(this object o, string methodName, params object[] args)
            {
                var type = o.GetType();
                var mi = type.GetMethod(methodName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
    
                if (mi != null)
                {
                    return (T)mi.Invoke(o, args);
                }
    
                throw new Exception($"Method {methodName} does not exist on type {type.ToString()}");
            }
    
    public static T CallNonPublicProperty<T>(this object o, string methodName)
            {
                var type = o.GetType();
                var mi = type.GetProperty(methodName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
    
                if (mi != null)
                {
                    return (T)mi.GetValue(o);
                }
    
                throw new Exception($"Property {methodName} does not exist on type {type.ToString()}");
            }
    

    And you can use them like this:

    var color= new Color();
    var result= color.CallNonPublicMethod<YourReturnType>(YourMethodName, param1, param2, ... param n);
    
    0 讨论(0)
提交回复
热议问题