Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..

like image 292
Yakov Avatar asked Feb 16 '15 17:02

Yakov


Video Answer


2 Answers

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

See PrivateType.

like image 179
Brian Rasmussen Avatar answered Sep 20 '22 06:09

Brian Rasmussen


Use below code with 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)
like image 40
dayanand Avatar answered Sep 22 '22 06:09

dayanand