Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Interface Mocks More Desirable than Subclass Mocks when Unit Testing?

When a class implements an interface, then it is easy to mock, but, you have to create an interface for it.

You can also mock by subclassing and overriding. If your base class provides a parameterless protected constructor, then your subclass mocks are not tied to changes in the base class constructor.

At first glance, it seems like the subclassing method to creating mocks is more desirable than creating interfaces for everything, but obviously, that's not how most people are doing it.

So, why are mocks based on interfaces considered a better practice than mocks based on subclassing?

like image 530
jmrah Avatar asked Aug 28 '15 12:08

jmrah


People also ask

Why do we need mocking in unit testing?

Mocking is a way to replace a dependency in a unit under test with a stand-in for that dependency. The stand-in allows the unit under test to be tested without invoking the real dependency.

Can you mock an interface?

mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called. We don't need to do anything else to this method before we can use it.

What is the difference between mock test and unit test?

In traditional unit testing, unit tests do assertions about states expected of either the system under test or its dependencies. With mock testing, no assertions are required from the unit tests themselves. Assertions are done by the mock objects.

Is mocking bad in unit testing?

Automated testing during software development involves many different techniques, one that shouldn't be used is mocking. Mocks are a distraction at best and provide false confidence at worst.


1 Answers

When you subtype and override, you have the risk of missing overriding one of the methods you should have overridden, and actually running the "production" code, which you'd want to isolate away from your test.

When you mock an interface, 100% of its behavior must be mocked. Whatever isn't explicitly stated by mocking will just throw an exception, and force you address it.

like image 77
Mureinik Avatar answered Oct 18 '22 05:10

Mureinik