本文介绍了Visual Studio中的PrivateObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Visual Studio 2019,并且在MSTest测试项目(.NET Core)中尝试使用PrivateObject
测试受保护的方法.
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())
但是出现以下错误
我也包括在内
using Microsoft.VisualStudio.TestTools.UnitTesting;
我认为应该包括PrivateObject
的
.
which I thought would include PrivateObject
.
有什么想法吗?
推荐答案
我认为PrivateObject
在.Net Core中不存在.您可以使用这些扩展来调用非公共成员.
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);
这篇关于Visual Studio中的PrivateObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!