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
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);