Home > Software design >  Prevent call to base class constructor using NSubstitute
Prevent call to base class constructor using NSubstitute

Time:11-19

Consider this type that is outside my control:

public class Foo : FooBase {

  public Foo(IBar bar)
    : base(bar) {                       // <---- here's the problem
  }

  // other stuff...

}

I can do this: Substitute.ForPartsOf<Foo>(Substitute.For<IBar>()). But it calls the base class' constructor, so everything breaks.

I thought I could use some DoNotCallBase magic or something similar, but couldn't find a way.

Is there some trick for handling this situation?

CodePudding user response:

No, DoNotCallBase on a mock works only on virtual members, but not on constructors. A constructor must call one of the base class constructors, this is strictly required by the .NET Framework. No mocking framework I know of can work around this issue.

However, what is the problem with calling the base class? You use an interface Mock, so with the right expectations on IBar, everything should work.

  • Related