在 C# 中使用具有多个参数的 PrivateObject 进行单元测试私有方法

Unit Test Private Method Using PrivateObject With Multiple Parameters in C#

我有一个 class ClassA 私有方法 DoSomething 像这样

private bool DoSomething(string id, string name, string location
  , DataSet ds, int max, ref int counter)

参数类型不同,最后一个参数是ref参数。

我想对这个方法进行单元测试,我知道我可以使用 PrivateObject 来这样做。但我不确定如何正确调用此方法。

我试过了

DataSet ds = new DataSet("DummyTable");
PrivateObject po = new PrivateObject(typeof(ClassA));
string id = "abcd";
string name = "Fiat";
string location = "dealer";

bool sent = (bool) po.Invoke(
    "DoSomething"
    , new Type[] { typeof(string), typeof(string), typeof(string)
        , typeof(DataSet), typeof(int), typeof(int) }
    , new Object[] { id, name, location, ds, 500, 120 });

,但出现此错误

System.ArgumentException : The member specified (DoSomething) could not be found. You might need to regenerate your private accessor, or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor.

我认为我做的一切都是正确的,但很明显,我不是。

更新和解决方案

想通了。从 Invoke 调用中删除 Type[] 修复它:

bool sent = (bool) po.Invoke(
    "DoSomething"
    //, new Type[] { typeof(string), typeof(string), typeof(string)
    //    , typeof(DataSet), typeof(int), typeof(int) } // comment this
    , new Object[] { id, name, location, ds, 500, 120 });

像 belove 一样删除 Type 并改用 Object。另请参阅上面的问题更新中的如何使用它

bool sent = (bool) po.Invoke("DoSomething", 
                new Object[] { id, name, location, ds, 500, 120 });