How do interfaces make unit testing and mocking easier?

mocking, unit-testing

Solution

It is the nature of the Interfaces to provide many implementations, thus enable mocking.

Especially in integration testing you are able to give your version of a dependency system mock-up (e.g. a web-service). Instead of actually calling a dependent system or even a module, or a complicated and difficult to instantiate type, you can provide a simplest interface implementation that will provide results needed for the unit test to complete correctly.

In addition to that, when you use in unit testing, an actual dependent type (call it BigGraph) hiding a complicated object model behind it, you are in fact do integration testing not unit testing. Your test can easily break if there is a bug in any of the dependent types (BigGraph), not the type you're testing, thus not unit-testing. Using mock-ups reduce risk of that happening.

I've seen many continuous integration systems showing dozens of errors for one bug, when they should show up one, or at most a couple, all because of too complicated object models, and incorrectly written unit-test - not using mock-ups.

Today mocking frameworks are more sophisticated (bytecode modification, etc.) than the old days, so sometimes interfaces or even virtual methods aren't always needed, but nerveless interfaces enable them.

Interfaces will not help if your object model is too complicated and cluttered (e.g. your interface relies heavily on other types/interfaces); then implementing/mocking all this is a pain.

Problem

It is often said that interfaces make mocking and unit testing an easier process. How do interfaces help with this?

Original source

Related problems