2

I have a class ClassA with private method DoSomething like this

private bool DoSomething(string id, string name, string location
  , DataSet ds, int max, ref int counter)

The parameters are of different types and the last parameter is a ref parameter.

I would like to unit test this method and I know I can use PrivateObject to do so. But I am not sure how do I properly invoke this method.

I tried this

DataSet ds = new DataSet("DummyTable");
PrivateObject po = new PrivateObject(typeof(ClassA));
string id = "abcd";
string name = "Fiat";
string location = "dealer";

bool sent = (bool) po.Invoke(
    "DoSomething"
    , new Type[] { typeof(string), typeof(string), typeof(string)
        , typeof(DataSet), typeof(int), typeof(int) }
    , new Object[] { id, name, location, ds, 500, 120 });

, but I get this error

System.ArgumentException : The member specified (DoSomething) could not be found. You might need to regenerate your private accessor, or the member may be private and defined on a base class. If the latter is true, you need to pass the type that defines the member into PrivateObject's constructor.

I think I am doing it all correct but obviously, I am not.

UPDATE AND SOLUTION

Figured it out. Removing Type[] from the Invoke call fixes it:

bool sent = (bool) po.Invoke(
    "DoSomething"
    //, new Type[] { typeof(string), typeof(string), typeof(string)
    //    , typeof(DataSet), typeof(int), typeof(int) } // comment this
    , new Object[] { id, name, location, ds, 500, 120 });
pixel
  • 9,653
  • 16
  • 82
  • 149
  • Figured it out, see UPDATE AND SOLUTION in the original post – pixel May 30 '17 at 23:08
  • 1
    If you have a solution, you better post an answer and check it as the correct one, instead of embedding the answer _inside_ your question. – Massimiliano Kraus Sep 26 '17 at 14:09
  • From a testing practices perspective, you don't test private methods directly. Private methods represent implementation details. You test the public methods of the class, and the private methods are exercised through the public methods. If you find it difficult to test your private methods in that fashion, it represents a *design problem* and the class should be split into smaller, composable classes and independently tested. – Daniel Mann Mar 21 '18 at 21:49

1 Answers1

3

Remove Type like belove and use Object instead. Also see how to use it in question update above

bool sent = (bool) po.Invoke("DoSomething", 
                new Object[] { id, name, location, ds, 500, 120 });
pixel
  • 9,653
  • 16
  • 82
  • 149