测试私有静态方法抛出MissingMethodException

Yak*_*kov 11 c# unit-testing privateobject.invoke

我有这门课:

public class MyClass
{
   private static int GetMonthsDateDiff(DateTime d1, DateTime d2)
   {
     // implementatio
   }
}
Run Code Online (Sandbox Code Playgroud)

现在我正在为它实施单元测试.由于该方法是私有的,我有以下代码:

MyClass myClass = new MyClass();
PrivateObject testObj = new PrivateObject(myClass);
DateTime fromDate = new DateTime(2015, 1, 1);
DateTime toDate = new DateTime(2015, 3, 17);
object[] args = new object[2] { fromDate, toDate };
int res = (int)testObj.Invoke("GetMonthsDateDiff", args); //<- exception
Run Code Online (Sandbox Code Playgroud)

mscorlib.dll中出现"System.MissingMethodException"类型的异常但未在用户代码中处理其他信息:尝试访问缺少的成员.

我究竟做错了什么?该方法存在..

Bri*_*sen 22

它是一种静态方法,因此请使用PrivateType而不是PrivatObject访问它.

请参见PrivateType.

  • 和`InvokeStatic()`而不是`Invoke()`来调用它. (8认同)

小智 9

使用以下代码与PrivateType

MyClass myClass = new MyClass();
PrivateType testObj = new PrivateType(myClass.GetType());
DateTime fromDate = new DateTime(2015, 1, 1);
DateTime toDate = new DateTime(2015, 3, 17);
object[] args = new object[2] { fromDate, toDate };
(int)testObj.InvokeStatic("GetMonthsDateDiff", args)
Run Code Online (Sandbox Code Playgroud)