Yakov Yakov - 1 month ago 14
C# Question

Test private static method throws MissingMethodException

I have this class:

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

Now I am implementing unit test for it.
Since the method is private, I have following code:

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

An exception of type 'System.MissingMethodException' occurred in mscorlib.dll but was not handled in user code
Additional information: Attempted to access a missing member.

What Am I doing wrong? The method exists..


It is a static method, so use PrivateType instead of PrivatObject to access it.

See PrivateType.