-1

I am trying to write unit tests for a private method with a string[] as parameter. Invoking a private method works with the PrivateObject class, however it did not when I tried invoking it with string[].

The test returns

System.NullReferenceException: Object reference not set to an instance of an object

on invocation.

This is the class which contains the method I need to invoke:

public class Program{
    public Program(){}

    private void TestCommand(string[] command){}
}

I tried the following:

Program program = new Program();
PrivateObject privateObject = new PrivateObject(program);

object[] parameters = new object[1] {
    new string[2] {
       "add",
       "rando"
    }
};

/* doesn't work either
object[][] parameters = new object[1][];
parameters[0] = new string[2];

parameters[0][0] = "add";
parameters[0][1] = "rando";*/

privateObject.Invoke("TestCommand", parameters);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
oddRaven
  • 672
  • 1
  • 7
  • 20
  • Your code should work as is. What does your real `TestCommand` actually do? – forsvarir Apr 11 '16 at 13:20
  • What do you mean with `doesn't work either`? Those are different things, not just different code for the same thing. – Toxantron Apr 11 '16 at 13:28
  • If the parameter list is `params object[]`, then the two ways of invoking are to pass the param as `privateObject.Invoke("TestCommand", new string[] {"add", "rando"})` or to use `privateObject.Invoke("TestCommand", new object[] {new string[]{"add", "rando"}})`. There are cases where the latter is required, but I think you are over-nesting your arrays. – Berin Loritsch Apr 11 '16 at 13:53
  • @SándorMátyásMárton PrivateObject does not have a TestCommand method https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privateobject.aspxx – oddRaven Apr 11 '16 at 17:53
  • @forsvarir "add rando" would add an animal with the name "rando". The method is called TestCommand because it will test if the command is valid. I figured the contents of the method were irrelevant to the question. – oddRaven Apr 11 '16 at 17:56
  • @Toxantron this was just about giving an example of something else I tried, among other attempts. – oddRaven Apr 11 '16 at 17:57

1 Answers1

0

Turned out there was nothing wrong with the invocation. Rather the exception occurred in a method called from within TestCommand. A field used in the method was not assigned. This was not clear at all from the error messages received in Visual Studio, it made it seem like the exception was at the Invoke method.

oddRaven
  • 672
  • 1
  • 7
  • 20