Search code examples
classinterfacemockingconcrete

What is the benefit of mocking an interface instead of a concrete class


Is there a benefit in mocking a concrete class vs an interface?

sample:

In my CustomerService class I call the CustomerDataProvider like

customerDataProvider.GetCustomers();

customerDataProvider could also be of type ICustomerDataProvider. When I want to test the logic inside the CustomerService only without going to the database then I have to mock the customerDataProvider object of type ICustomerDataProvider OR CustomerDataProvider.

Where is the advantage in mocking one type over the other?


Solution

  • The primary benefit to mocking an interface rather than a class is that it's simpler - interfaces can't be sealed/final, they can't have methods you can't override, and they can't have unusual construction semantics. Mocking libraries can take away a lot of the headaches of mocking classes, but they can't make up for untestable design.

    The primary reason to mock classes instead of interfaces is: sometimes you only have a class. If you're doing your own design and implementation then you can make the choice to build one or the other. If you're consuming someone else's library, you have to deal with what it provides.