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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With