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?
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.
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.
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.
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.
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.
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