How do you test private methods?

This morning I read a post by Davy Brion who was explaining a technique to test private methods. Although the post was interesting, it was a comment by Rafferty Uy that got me thinking. He suggests that you make your method protected instead of private and have the testing class inherit from this class. There is much debate as to whether you should be testing private methods at all, and as I am fairly new to unit testing, I have only ever tested my public methods.

From Microsoft:-


The type or member can only be accessed by code in the same class or struct, or in a derived class.


So that is fine if your tests live in the same project as the code being tested. You just inherit from the class. If however you have all your tests in a separate project, then you simply need to have a reference to the .dll or .exe of your main project with the methods that need testing. Add the namespace to your using list and inherit the class in your test class.

   1: using NUnit.Framework;
   2: using Spike.PrivateMethodTest;
   4: namespace Spike.UnitTests
   5: {
   6:     [TestFixture()]
   7:     public class Class1 : Spike.PrivateMethodTest.Program
   8:     {
   9:         [Test()]
  10:         public void TestPublicMethod()
  11:         {
  12:             string expectedValue = "this is public";
  13:             string actualValue = Program.MyPublicMethod();
  14:             Assert.AreEqual(expectedValue, actualValue);
  15:         }
  17:         [Test()]
  18:         public void TestPrivateMethod()
  19:         {
  20:             string expectedValue = "this is private";
  21:             string actualValue = Program.MyPrivateMethod();
  22:             Assert.AreEqual(expectedValue, actualValue);
  23:         }
  24:     }
  25: }

This technique seems by far the simplest I have come across to allow you to test private methods.


  • There's always Reflection for Privates as well.

  • Thanks guys, great input. That's 3 other ways to test private methods. I think I will have to look deeper into these methods and see how they can be integrated into our CI environment. Enough content for a post I think. Watch this space.

  • Good day I was luck to discover your Topics in digg
    your post is impressive
    I get a lot in your Topics really thanks very much
    btw the theme of you website is really fabulous
    where can find it

Comments have been disabled for this content.