Search code examples
.netvb.netinheritancevirtualoverriding

Override base method call in all subclasses without inheriting each subclass (VB.NET)


for testing purposes, I need to override a specific method call, which is currently implemented in a base class.

 Public Overridable Function CreateFactory(Of TFactory As {IManagerFactory(Of IManager), Class})() As TFactory

I want to avoid having to create an inheriting class for each existing subclass of that base class (ie. CLTestableAccountManager for CLAccountManager which inherits from CLBase etc.).

Public Class CLTestableAccountManager
  Inherits CLAccountManager

    Public Overrides Function CreateFactory(Of TFactory As {IManagerFactory(Of IManager), Class})() As TFactory

While this works, it would lead to a lot of duplicated code due to the many classes this would apply to. The method must only be overridden when used in the context of unit tests so I shouldn't really touch the base class implementation (which is virtual/overridable).

Unfortunately, I cannot simply do something like

Public Class CGenericBaseOverrider(Of TBase As {CLBase})
  Inherits TBase

to implement a generic way for overriding the method for all subclasses of CLBase.

Can anyone point me in a direction as to how this could be solved?


Solution

  • Can you use composition instead of inheritance?

    In other words, for testing purposes create a type which implements the same interface (introduce an interface if you don't have one) and delegates all the calls apart from CreateFactory to whatever production code you've got - but performs your custom behaviour for that one call.