【问题标题】:Unit Test Private Method Using PrivateObject With Multiple Parameters in C#在 C# 中使用具有多个参数的 PrivateObject 进行单元测试私有方法
【发布时间】:2017-10-31 13:36:44
【问题描述】:

我有一个类 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 });

【问题讨论】:

  • 想通了,请参阅原帖中的更新和解决方案
  • 如果您有解决方案,最好发布一个答案并检查它是否正确,而不是将答案嵌入您的问题中。
  • 从测试实践的角度来看,您不会直接测试私有方法。私有方法代表实现细节。你测试类的公共方法,私有方法通过公共方法来执行。如果您发现难以以这种方式测试您的私有方法,则它代表了一个设计问题,并且该类应该被拆分成更小的、可组合的类并进行独立测试。

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2023-03-14
    • 2014-08-10
    相关资源
    最近更新 更多