I am working on my first project using TDD and have applied a bit of brick wall when it comes to inheritance.
For example, if I have something like this
public interface IComponent { void MethodA(); void MethodB(); } public class Component : IComponent { public virtual void MethodA() {
then I cannot test ExtendedComponent in isolation because it depends on Component.
However, if I use composition to create an ExtendedComponent, like this
public class ExtendedComponent : IComponent { private readonly IComponent _component; public ComponentB(IComponent component) { _component = component; } public virtual void MethodA() { _component.MethodA();
Now I can test ExtendedComponent in isolation, mocking the wrapped IComponent.
The disadvantage of this approach is that if I want to add new methods to IComponent, then I have to add new methods to Component and ExtendedComponent and any other implementations, which can be many. Using inheritance, I could just add a new method to the base component and it would not break anything.
I really want to be able to test cleanly, so I prefer a compositional route, but I am concerned that the unit test capability is not a good reason to always use composition over inheritance. In addition, adding functionality at a basic level will require the creation of many tedious delegation methods.
I would really like advice on how other people approached this issue.
source share