If you have an interface for all objects / classes

As part of our process improvement, we are trying to ensure that all of our projects have suitable unit tests, since a little education is needed in the house, and I am trying to figure out what exactly is the best way to ensure that we make our classes as “testable” as possible.

I suspect that we will begin to move along the route of the Mock object, and in most examples I saw that they interact to simulate the implementation of objects. So my question is, should we ensure that ALL classes have an interface from which they are derived?

If not for the process that you would suggest when defining classes that should have an interface to allow them to be mocked?

+4
source share
3 answers

Not. Having interfaces on all classes / objects will create unnecessary overhead without bringing any additional benefits.

The general rule is that your classes should depend on abstractions, and not on specific implementations, so I would suggest using “dependencies” as a starting point, and any class that is an external dependency on another class should implement an interface.

+7
source

"defining classes that must have an interface that allows them to mock"

It is not that difficult. I do not quite understand why you are asking. Perhaps you have other deeper questions.

You look at the design and find all the pairs of classes that are related, and ask: “A depends on B”, if so, B needs to be mocked so that A can be tested independently.

+3
source

YAGNI says until needed. I say: if you use Test Driven Design, then I think that you should use tests to dictate the design.

As a specific example, I am writing a virtual machine that can run embedded bytecode. The interface of the outside world is the Runtime interface. The client uses it to run functions by name, global queries, etc.

Implementing Runtime requires many different components, one of which is VirtualMachine, which controls access to the stack, memory, registers, etc.

In unit testing, the idea is to take each object and test it separately from the rest of the world. However, the runtime depends on VirtualMachine. To disconnect a virtual machine from Runtime, it needs to be mocked. This means that VirtualMachine must be derived from an interface common to MockVirtualMachine.

Consequently, tests dictate that VirtualMachine should be inherited from the interface. I did not need to do this until then.

+2
source

All Articles