PrivateObject in Visual Studio

前提是你 提交于 2020-02-16 08:15:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!