Tim Barrass Tim Barrass - 1 year ago 203
C# Question

C#: Mocking and testing protected (or private) methods in sealed classes -- approaches

I have a sealed class with protected methods whose behaviour I want to test. This makes it hard to test directly, and hard to mock.

It's in a codebase that wasn't developed in a TDD manner, and I'm now adding unit tests for specific functionality.

What are the general approaches possible in this case? At the moment I have:

  1. Have the class unsealed. Then create a proxy or adapter derived from the class in our test code to tunnel access to the protected method.

  2. Factor out the behaviour in the protected method to a delegate/functor, and re-inject it. Then test the factored out behaviour independently.

  3. Test by calling the closest public method in the inheritance hierarchy that uses the protected method. Potentially leads to lots of mocking, and exposure to risk when code other than that under test changes -- creating fragile tests.

  4. Use reflection to get access to the protected method. Then call it directly.

Are there any more?

Answer Source

A protected method in a sealed class is effectively the same as private (I guess if you seal a derived class where the base class has a protected member these can come up naturally.)

And there's no point testing private methods. Because they have no public behavior except that which is accessible through the public methods of the defining class, their behavior should be tested by testing the public methods.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download