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

时间:2017-05-30 22:45:47

标签: c# unit-testing nunit parameter-passing privateobject.invoke

我有一个类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:   无法找到指定的成员(DoSomething)。您可能需要重新生成私有访问者,   或者该成员可以是私有的,并在基类上定义。如果后者为真,则需要传递类型   将成员定义为PrivateObject的构造函数。

我认为我这样做是正确的,但显然,我不是。

更新和解决方案

想出来。从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 });

1 个答案:

答案 0 :(得分:1)

删除类似belove的类型并改为使用Object。另请参阅上面的问题更新如何使用它

<asp:CheckBox ID="chkResOther" runat="server" onclick="RadioControl(this); otherFunction();" Text="Other" />
相关问题