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?
The commercial edition allows you to mock concrete objects without having to change anything in their interface. This is an elevated feature.
You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces. However, there are a few limitations you should be aware of. The classes to be mocked can't be static or sealed, and the method being mocked should be marked as virtual.
5 Answers. Show activity on this post. In theory there is absolutely no problem mocking a concrete class; we are testing against a logical interface (rather than a keyword interface ), and it does not matter whether that logical interface is provided by a class or interface . In practice .
The three key steps to using mock objects for testing are: Use an interface to describe the object. Implement the interface for production code. Implement the interface in a mock object for testing.
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 a 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.
I should add that by attempting to mock concrete types you are defeating the purpose of mocking frameworks. You should be mocking roles, not types. Therefore working to an abstraction, in this case an interface is a great thing to do.
Another reason is how interfaces work, interfaces state a contract but not behavior. They should be used when you have multiple implementations, and I class testing as a behavior hence the valid reason to introduce a new interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With