问题
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 trying to do something like following
PrivateObject private= new PrivateObject(new Color())
But I get the following error
PrivateObject could not be found are you missing a using directive or an assembly reference?
I am also including
using Microsoft.VisualStudio.TestTools.UnitTesting;
which I thought would include PrivateObject
.
Any ideas?
回答1:
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);
来源:https://stackoverflow.com/questions/60067717/privateobject-in-visual-studio