RSS Feed Subscribe to RSS Feed

 

Testing private methods in .Net

Feeling the need to test private methods is usually a sign that your code needs refactoring. The recommended approach is that you test your code via it’s public interface. Since your private methods are only accessible via those public methods, it goes that if you have thoroughly testing via the public interface, your private methods will have been tested too.

Still, there can be times testing private methods can be useful. For example, while dealing with either legacy code or when using it as a temporary step while refactoring.

How do you do this in .Net?

I know how to deal with this Java. My typical order of preference is usually:

  1. Refactor
  2. Change the visibility (e.g. in Java, from private to package level)
  3. Use Reflection
  4. Use PowerMock (allows you to test privates, but can be slow)

But I am giving a talk on testing to what I expect will be mostly .Net folks soon, so I thought I would do some research into it. Disclaimer: I am not a .Net developer! So take all the following with a pinch of salt, and do your own research, but here are some approaches I think would work for testing private methods in .Net code.

1. Private Accessors

According to this How to Test a Private Method article on msdn.microsoft.com, you can test both public and private methods using unit tests, and that although this can be done manually using reflection, the recommended way is to automatically generate the tests using Visual Studio.

2. Reflection

If you do choose to use reflection to test the private method directly, this snippet of code (from ) may help:

PrivateClass obj = new PrivateClass(); // Class containing private obj
Type t = typeof(PrivateClass); 
var x = t.InvokeMember("PrivateFunc", 
    BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Public |  
        BindingFlags.Instance, null, obj, new object[] { 5 });

3. InternalsVisibleToAttribute

If you are trying to test an internal method, which in .Net means it visible only within the current assembly, one option is to use the InternalsVisibleToAttribute class. This “Specifies that types that are ordinarily visible only within the current assembly are visible to a specified assembly.”

 

 

Tags: ,

Leave a Reply