Testing Private & Protected Members of a Class

In my last blog post, someone asked me you can write unit tests for a private or protected method.  I gave part of the response in a comment, but I need to give a more detailed description.

Focus on the public API of your system

First and foremost, I focus on testing the public API.  You should be able to test all of the code branches in your private methods by adequately testing the public methods in your system.  Using tools like NCover can help you analyze how well your tests are actually testing your system.  I don’t try to get 100% coverage, but I typically have above 80% as a normal target.

Testing Protected Members

There are times when you do need to test protected members of a class.  If you are inheriting from a class that you do have the source code to (like say Controller) and you override a protected method, it is possible to test that.  While it should be possible to test protected member through the public api, it is relatively simple to do it and doesn’t really break any encapsulation rules in your application.

It is actually very easy.  All you need to do is create a test class that inherits from you and add a public method that call the protected method in question.  Here is an example.

public class ClassWithProtectedMember
    {
        
protected int UltimateQuestionAnswer() { return 42; }
    }

    public class ProtectedMemberAccessor : ClassWithProtectedMember
    {
        
public int ExecuteUltimateQuestionAnswer(){
            
return base.UltimateQuestionAnswer();}
    }
    [
TestFixture]
    
public class ProtectedMemberSpecs {

        [Test]
        
public void should_give_us_the_answer_to_life_universe_and_everything()
        {
            
var wrapper = new ProtectedMemberAccessor();
            
Assert.That(wrapper.ExecuteUltimateQuestionAnswer(),Is.EqualTo(42));
        }
    

This is a very simple and straightforward approach, but is very effective in testing some hidden members in you system.

This entry was posted in c#, Testing. Bookmark the permalink. Follow any comments here with the RSS feed for this post.