views:

1082

answers:

2

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?

+1  A: 

If the class does not implement an interface or if the mocking framework allows partial mocks then you would want to be able to mock the class. In the former case, because there is no interface to mock. In the latter, so you can inherit existing behavior from the class that you don't want to mock out.

Typically, though, you would want your classes to depend on interfaces when available. In that case, you needn't mock a class that implements the interface. You should just mock the interface itself to avoid any dependencies in your test that don't exist in the class under test.

tvanfosson
+6  A: 

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.

Mike Scott