問題很簡單但很難繞過 - 我需要測驗私有方法而不是簡單地更改代碼以將其公開。這樣做不會是世界末日,但此類包含一個公共方法和一組專用于該公共方法的私有方法,更改它是不好的做法。
我設法在網上找到了“解決方案”,但它似乎不起作用。測驗失敗并出現例外System.Reflection.TargetException : Object does not match target type.。
這是簡化的代碼:
private Class _class;
private List<Item> _list;
private List<Item> _resultList;
[SetUp]
public void SetUp()
{
_class = new Class();
_list = new List<Item>();
_resultList = new List<Item>();
//do stuff to prepare data
}
[Test]
public void TestMethod_Equal()
{
var method = GetMethod("PrivateMethodName");
var result = method.Invoke(this, new object[] { _list }); //this private method needs `List<item>`
Assert.That(_resultList, Is.EqualTo(result));
}
private MethodInfo GetMethod(string methodName) //the online solution
{
if (string.IsNullOrWhiteSpace(methodName))
Assert.Fail("methodName cannot be null or whitespace");
var method = this._class.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
if (method == null)
Assert.Fail(string.Format("{0} method not found", methodName));
return method;
}
uj5u.com熱心網友回復:
您需要類的實體才能針對該實體呼叫方法。在為類定位時,您還需要使用相同型別的所述實體MethodInfo。我已將您的代碼改編為以下示例:
void Main()
{
var myInstanceUnderTest = new MyConcreteClass();
var method = myInstanceUnderTest.GetType().GetPrivateMethod("SomePrivateMethod");
method.Invoke(myInstanceUnderTest, null);
}
public class MyConcreteClass
{
private void SomePrivateMethod()
{
Console.WriteLine("I ran!");
}
}
public static class Helpers
{
public static MethodInfo GetPrivateMethod(this Type myType, string methodName) //the online solution
{
if (string.IsNullOrWhiteSpace(methodName))
throw new Exception("methodName cannot be null or whitespace");
var method = myType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
if (method == null)
throw new Exception(string.Format("{0} method not found", methodName));
return method;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535017.html
標籤:C#。网单位
