views:

69

answers:

2

I want to use Moq, but I am using Nhibernate and I didn't create interfaces for all my Model classes (POCO classes).

Do I have to create an interface for each class for me to be able to moq my POCO classes?

+1  A: 

The classes/methods you are Mocking either need to implement an interface or be virtual. You can test any class/method as long as its accessible, but there's no way to mock something that cannot be overridden or implemented explicitly.

Andrew
+4  A: 

You can mock virtual methods, but its best if you use an interface.

Reason I say this is as follows:

var mockObject = new Mock<IMyObject>();

If you use an virtual method it becomes:

var mockObject = new Mock<MyObject>(params...);

You are forced to include the parameters for concrete objects, but you obviously don't need to for interfaces. All tests using concrete classes will require updating if you decide to change the class' constructor at a later date. I've been burned by this in a past so try not to use virtual methods for testing anymore.

Any reason is how interfaces work, interfaces state a contract but no behaviour. They should be used when you have multiple implementations, and I class testing as a behaviour hence the valid reason to introduce a new interface.

Finglas
I'd agree to favor interfaces. There are a few cases where abstract classes make more sense, though (such as the Template Method Pattern). As usual, these are guidelines - use your own judgment.
TrueWill