测试私有静态方法抛出 MissingMethodException

Test private static method throws MissingMethodException

我有这个class:

public class MyClass
{
   private static int GetMonthsDateDiff(DateTime d1, DateTime d2)
   {
     // implementatio
   }
}

现在我正在对其进行单元测试。 由于该方法是私有的,我有以下代码:

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

'System.MissingMethodException' 类型的异常发生在 mscorlib.dll 但未在用户代码中处理 附加信息:试图访问丢失的成员。

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

int res = (int)typeof(MyClass).InvokeMember(
                name: "GetMonthsDateDiff", 
                invokeAttr: BindingFlags.NonPublic |
                            BindingFlags.Static |
                            BindingFlags.InvokeMethod,
                binder: null, 
                target: null, 
                args: args);

Invoke方法是找不到的。 Object class 没有 Invoke 方法。我认为您可能正在尝试使用 this Invoke,它是 System.Reflection.

的一部分

你可以这样使用,

var myClass = new MyClass();
var fromDate = new DateTime(2015, 1, 1);
var toDate = new DateTime(2015, 3, 17);
var args = new object[2] { fromDate, toDate };

var type = myClass.GetType();
// Because the method is `static` you use BindingFlags.Static 
// otherwise, you would use BindingFlags.Instance 
var getMonthsDateDiffMethod = type.GetMethod(
    "GetMonthsDateDiff",
    BindingFlags.Static | BindingFlags.NonPublic);
var res = (int)getMonthsDateDiffMethod.Invoke(myClass, args);

但是,您不应该尝试测试 private 方法;它过于具体并且可能会发生变化。您应该改为 DateCalculator class 的 public,它在 MyClass 中是私有的,或者也许,将其设为 internal,这样您只能在您的内部使用组装.

它是一个静态方法,所以使用 PrivateType 而不是 PrivatObject 来访问它。

参见PrivateType

使用下面的代码和 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)
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 };

//The extra flags
 BindingFlags flags = BindingFlags.Static| BindingFlags.NonPublic
int res = (int)testObj.Invoke("GetMonthsDateDiff",flags, args);