Why are front-end Mocks more desirable than subclasses of Mocks in unit testing?

When a class implements an interface, then it is easy to make fun of it, but for this you need to create an interface.

You can also mock up by subclassing and overriding. If your base class provides a constructor without parameters, then your mocks subclasses are not tied to changes in the constructor of the base class.

At first glance, it seems that the subclass method for creating mocks is more desirable than creating interfaces for everything, but obviously this is not how most people do it.

So, why is interface-based mocks considered best practice than subclass-based mocks?

+5
source share
2 answers

Contrary to most beliefs, even if you are conducting Test-Driven Development (TDD), you should still follow good design practice. The trick is to make the API testable and well-designed. TDD is not a design methodology , but a feedback method.

Therefore, this is not a matter of the Mocks interface versus the Mocks subclass, but rather a matter of interfaces and subclasses.

This is a really old discussion, which was supposed to end in 1994; in Design Patterns , we learn that we need to maintain composition over inheritance .

There is a long discussion of this topic, but, in short, in languages ​​with one inheritance, based on the design of the inheritance API, it is necessary to limit all future variability to other (but unforeseen) dimensions. Inheritance in such languages ​​is simply too restrictive. Since all major object-oriented languages ​​(Java, C #, Ruby) have one inheritance, you should see that most object-oriented code bases avoid inheritance correctly.

When a design is based on composition over inheritance, it follows that if you use mock objects, you will mock interfaces, not base classes.

+5
source

When you subtype and redefine, you have the risk of losing the override of one of the methods that you must override and actually run the β€œproduction” code that you want to isolate from your test.

When you mock an interface, 100% of its behavior needs to be mocked. No matter what is not explicitly indicated by mockery, you simply throw an exception and force it to refer to it.

+2
source

All Articles