Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you prevent the base class constructor from being called with Moq?

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.

like image 421
learnerplates Avatar asked May 18 '12 15:05

learnerplates


People also ask

How to avoid calling base class constructor in c#?

To ignore a base class constructor, use the BaseConstructor behavior of Isolate. Fake. Instance().

Does base class constructor get called automatically?

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.

Can we override base class 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.

Which is the correct way to call the base class constructor?

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.


1 Answers

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).

like image 109
Alex Peck Avatar answered Oct 29 '22 18:10

Alex Peck