-2

In Java you can invoke a private method like so:

Method m = obj.getClass().getDeclaredMethod("foo", null); 
m.setAccessible(true);
m.invoke("bar");

What is the equivalence in C#? I need to call a private method in the Unit Test.

Hanjun Chen
  • 544
  • 4
  • 11
  • `I need to call a private method in the Unit Test` - you should read some of the answers to this question: https://stackoverflow.com/a/34586/558486 – Rui Jarimba Oct 16 '18 at 18:32
  • Checking your tags, you really do need to check [this question](https://stackoverflow.com/questions/358196/c-sharp-internal-access-modifier-when-doing-unit-testing) – Cleptus Oct 16 '18 at 18:33
  • @bradbury9 the problem is that the OP wants to invoke private methods, not accessing internal classes in another assembly.... :-( – Rui Jarimba Oct 16 '18 at 18:35
  • @bradbury9 I am examining the top 2 answers of that question. Thanks – Hanjun Chen Oct 16 '18 at 18:37
  • @RuiJarimba Yeah, invoking private methods to do testing, looks like XY problem, should use internal and then there is no need to reflection – Cleptus Oct 16 '18 at 18:37
  • You probably got down-voted because if you look in the System.Reflection namespace, you will see a method called `GetMethod` on the `Type` class. It's pretty easy to figure out. Also, if you search for "c# reflection invoke private method" you get lots of results. – Flydog57 Oct 16 '18 at 18:38

1 Answers1

1

If you have access to the MSTest Framework, you can create a PrivateObject instance, which is a wrapper that can be used to access private methods and fields of an object instance.

https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.privateobject?redirectedfrom=MSDN&view=mstest-net-1.2.0

You can use the PrivateObject.Invoke() methods to call private methods from the object in question.

As a side note, it is sometimes considered bad practice to have to access private methods in order to do unit tests. I know it's not always possible, but you should also consider re-evaluating your code architecture to make it more UnitTest friendly as to not require this kind of workaround.