测试私有静态方法抛出MissingMethodException异常。

14

我有这个类:

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'的异常,但未在用户代码中处理 附加信息:尝试访问一个不存在的成员。

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

5个回答

27

这是一个静态方法,因此请使用 PrivateType 而不是 PrivatObject 来访问它。

请查看 PrivateType


10
使用InvokeStatic()代替Invoke()来调用它。 - Nigel Touch

11

使用以下代码与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)

4
Invoke 方法是找不到的。 Object 类没有 Invoke 方法。我认为你可能想使用 这个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类的public方法,该类在MyClass中是私有的,或者将其设置为internal,这样你只能在程序集内使用。


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

1
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); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接