Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For me to use Moq, do all my classes have to implement an interface?

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?

like image 287
mrblah Avatar asked Dec 25 '09 19:12

mrblah


People also ask

Can you mock without an interface?

The commercial edition allows you to mock concrete objects without having to change anything in their interface. This is an elevated feature.

Can you mock a class with Moq?

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.

Can you mock a concrete class?

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 .

How do I mock a class in NUnit?

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.


1 Answers

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.

like image 57
Finglas Avatar answered Oct 23 '22 07:10

Finglas