Reputation: 2005
I am trying to test a private the following private methods
public class Test
{
private bool PVTMethod1(Guid[] Parameter1)
{
return true;
}
private bool PVTMethod2(RandomClass[] Parameter2)
{
return true;
}
}
public class RandomClass
{
public int Test { get; set; }
}
using the following test method
[TestClass]
public TestClass1
{
[TestMethod]
public void SomUnitTest()
{
Test _helper = new Test();
PrivateObject obj = new PrivateObject(_helper);
bool response1 = (bool)obj.Invoke("PVTMethod1", new Guid[0]);
bool response2 = (bool)obj.Invoke("PVTMethod2", new RandomClass[0]);
}
}
The second Invoke fails with an System.MissingMethodException.
It seems to not find the method when using a complex type as a array parameter
Upvotes: 1
Views: 266
Reputation: 81513
If i understand this correctly, this is a quirk to do with how clr works out param arrays. This gets quite in depth and i have seen Eric Lippert talk about it several times.
A method with a params array may be called in either "normal" or "expanded" form. Normal form is as if there was no "params". Expanded form takes the params and bundles them up into an array that is automatically generated. If both forms are applicable then normal form wins over expanded form.
The long and the short of it is: mixing params object[] with array arguments is a recipe for confusion. Try to avoid it. If you are in a situation where you are passing arrays to a params object[] method, call it in its normal form. Make a new object[] { ... } and put the arguments into the array yourself.
So to fix this
bool response2 = (bool)obj.Invoke("PVTMethod2", (object)new RandomClass[0]);
or
bool response2 = (bool)obj.Invoke("PVTMethod2", new object {new RandomClass[0]});
I wont pretend to know the insides of the CLR, however if you are interest you could check out thse questions
Attribute with params object[] constructor gives inconsistent compiler errors
C# params object[] strange behavior
Why does params behave like this?
Is there a way to distingish myFunc(1, 2, 3) from myFunc(new int[] { 1, 2, 3 })?
Upvotes: 2