Use Moq to mock Constructor?

If you don't want to use your constructor parameters you might pass with It.IsAny() method while you mocking it. It would pass null value to it. It would be much more readable when you use this method instead of writing null.


It sounds as if you have a code smell - the constructor is doing too much work. The article includes a set of fixes for such scenarios. Basically the answer is to only perform assignment in constructors, not execute business logic.


var myMockBOC = new Mock<BusinessObjectContext>(null, null);

This will pass nulls in for your two parameters.

Another approach would be to create an internal constructor meant for test usage only, and use InternalsVisibleTo to allow your test assembly to use it. Unfortunately this has a big drawback in that if you sign your assemblies, Moq is unable to use the constructor. This is supposed to be addressed in the 4.0 release of Moq though.