19

I am trying to unit test private method. I saw example below on this question

Class target = new Class();
PrivateObject obj = new PrivateObject(target);
var retVal = obj.Invoke("PrivateMethod");
Assert.AreEqual(retVal);

My private method has 2 ref params. How to pass them?

Community
  • 1
  • 1
eomeroff
  • 9,599
  • 30
  • 97
  • 138
  • 3
    Have you looked at the overloads for [`Invoke`](http://msdn.microsoft.com/en-us/library/ms243741.aspx)? Do none of them work for you? – D Stanley Mar 18 '14 at 19:30
  • try -> `obj.Invoke("PrivateMethod",ref yourparmarray);` – Sudhakar Tillapudi Mar 18 '14 at 19:31
  • @DStanley Yes, I have looked here http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privateobject.aspx but not sure how to use. I am missing example. – eomeroff Mar 18 '14 at 19:32
  • @TomTom You can not be sure what I did. Surely I did same search around and did not find anything helpful. – eomeroff Mar 18 '14 at 19:34
  • 2
    @eomeroff If you did some "search around" then it is good to include your findings in the question, to explain what exactly don't you understand from the documentation. – BartoszKP Mar 18 '14 at 19:35
  • 2
    Just as an aside, I and many others would suggest not unit testing private methods directly. By all means ensure that all logic paths are covered, but if you *can't* reach it from a public method, you can be sure that line of logic is dead code. – Magus Mar 18 '14 at 19:37
  • @BartoszKP You must admit that it is going too far. People who try to demystify MSDN while trying to solve the problem are true heroes. – eomeroff Mar 18 '14 at 19:39
  • @eomeroff What is going too far? Sorry, I don't understand your comment. – BartoszKP Mar 18 '14 at 19:44
  • Please, do not include information about a language used in a question title unless it wouldn't make sense without it. Tags serve this purpose. – Ondrej Janacek Mar 18 '14 at 19:48

3 Answers3

28

If you pass the argument array, then any ref parameters will be populated in place:

bool p1 = true; // can be others values
bool p2 = false; // can be others values
object[] args = new object[2] { p1, p2 };
var retval = obj.Invoke("PrivateMethod", args);

p1 = (bool)args[0];
p2 = (bool)args[1];
Emiliano
  • 698
  • 9
  • 30
Lee
  • 142,018
  • 20
  • 234
  • 287
3

First create an object array of your parameters. the array should then contain the new references:

Class target = new Class();
PrivateObject obj = new PrivateObject(target);
object[] args = new object[] {arg1, arg2};
var retVal = obj.Invoke("PrivateMethodWithArgs", args);
Assert.AreEqual(retVal);

Debug.WriteLine(args[0]);
Debug.WriteLine(args[1]);
D Stanley
  • 149,601
  • 11
  • 178
  • 240
1

Try This:

object [] myarray=new object[]{param1,param2};
var retVal = obj.Invoke("PrivateMethod",ref myarray);
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67