How do you prevent the base class constructor from being called with Moq?
I'm unable to Mock an object with Moq because the base classes constructor is being called and it requires real objects, so I want to stop the base class constructor from being called.
var parametersMoq = new Mock<MyDerivedClass>(null, "Params", null){ CallBase = false, };
_storedProcedureAccessor._parameters = parametersMoq.Object;
MyDerivedClass's base class constructor is causing me issues.
To ignore a base class constructor, use the BaseConstructor behavior of Isolate. Fake. Instance().
If a base class has a default constructor, i.e., a constructor with no arguments, then that constructor is automatically called when a derived class is instantiated if the derived class has its own default constructor.
Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. But, a constructor cannot be overridden.
For multiple inheritance order of constructor call is, the base class's constructors are called in the order of inheritance and then the derived class's constructor.
There is no way to prevent the base class constructor from being invoked.
If you can edit the base class, you should replace the fixed dependencies with abstractions (e.g. an interface, abstract class or a delegate).
If you can't edit the base class, and you really need to be able to substitute the dependencies with test friendly fakes to write your unit tests, you need to do a bit more work (e.g. wrap the problematic base class in an abstraction, then use composition instead of inheritence, and depend on the new abstraction).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With