The difference between Moq-ing a class or interface


I've been using moq to mock objects in my unit tests and I've seen on the site about moq that it is able to mock both classes and interfaces.

I had a discussion with one of my work mates the other day and they stated that there is never a reason to mock classes and I should only mock interfaces.

I didn't really have an answer to that….and I can't seem to find any answer to that on the moq site either.

Is it true that one should never mock classes? I'd say no since if that were true then Moq wouldn't even allow it….So then is there a time where it is better to mock a class over an interface? What is the difference between mocking a class vs mocking an interface? Or does it really just a preference thing?

Best Solution

Mocking a class is perfectly valid. With MoQ, you can only mock virtual methods and properties on a class, though.

It's useful when you have abstract base classes instead of interfaces, or classes with default implementations and virtuals as extension points. There are many cases where you don't have access to the source code of classes you need to mock. There are many examples in the .Net framework, e.g. MembershipProvider.