Search code examples
c#unit-testingtddnaming-conventionsdesign-patterns

What is the name of the pattern?


I often design system where I have a class in my system that has a bunch of protected methods. The protected methods are that because they should be accessible to specializations, and as such, I consider the protected methods to be a contract between my general class and any specialized classes.

Therefore I want to test that these methods behave correctly, so my unit tests will need to access the protected methods, something that is not possible in c#, except by using dirty hacks like reflection.

The solution I normally choose is that I create a specialized class inside my unit test that exposes these protected methods as public. Because I always keep the unit tests in a separate assembly, the system code itself does not have access to these classes, and inside my system code, the protected function remains protected.

// In the system code assembly
namespace MySystem {
    public class SomeClass {
        protected void DoSomething() {
            ...
        }
    }
}

// In the unit test assembly
namespace MySystem.Unittests {
    public class SomeClass2 : SomeClass {
        public new void DoSomething() {
            base.DoSomething();
        }
    }
}

My unit test is now able to test the behaviour of the protected member on the parent class by instantiating the specialized class.

I also use this even further to be able to mock the object and mock function calls to protected virtual functions, but that code is a little more complex, so I'll just cut that out.

I find this way of accomplishing this task to be so straight forward that I cannot possibly be the only person doing this, and so I assume that there must be a common naming convention for this?


Solution

  • I have only done this when I don't control the class needed to be tested. Charles points out what you can do in .NET when you control the source code.

    Your case is a bit different in that your class is intended to be used as a superclass, so testing it via a subclass makes a lot of sense (since the class isn't intended to stand on its own). In this case, you are basically doing a variant of Test-Specific Subclass. The pattern described in the link is more about overriding behavior, and is very useful if you have a class that was not written test first and has a high coupling, it is a good way to tease apart the dependency (usually as an intermediate step to getting a separate class passed as a parameter). In your case, the "overriding" is for the purpose if increasing access, but it seems to fit the same pattern.