Mocking

Everyone who has done any of the applications more complicated than Hello World knows that Java code is full of dependencies. There can be classes and methods written by other members of the team, third-party libraries, or external systems that we communicate with. Even libraries found inside JDK are dependencies. We might have a business layer that communicates with the data access layer which, in turn, uses database drivers to fetch data. When working with unit tests, we take dependencies even further and often consider all public and protected methods (even those inside the class we are working on) as dependencies that should be isolated.

When doing TDD on the unit tests level, creating specifications that contemplate all those dependencies can be so complex that the tests themselves would become bottlenecks. Their development time can increase so much that the benefits gained with TDD quickly become overshadowed by the ever-increasing cost. More importantly, those same dependencies tend to create such complex tests that they contain more bugs than the implementation itself.

The idea of unit testing (especially when tied to TDD) is to write specifications that validate whether the code of a single unit works regardless of dependencies. When dependencies are internal, they are already tested, and we know that they do what we expect them to do. On the other hand, external dependencies require trust. We must believe that they work correctly. Even if we don't, the task of performing deep testing of, let's say, the JDK java.nio classes is too big for most of us. Besides, those potential problems will surface when we run functional and integration tests.

While focused on units, we must try to remove all dependencies that a unit may use. Removal of those dependencies is accomplished through a combination of design and mocking.

The benefits of using mocks include reduced code dependency and faster text execution.

Mocks are prerequisites for the fast execution of tests and the ability to concentrate on a single unit of functionality. By mocking dependencies external to the method that is being tested, the developer is able to focus on the task at hand without spending time setting them up. In a case of bigger or multiple teams working together, those dependencies may not even be developed. Also, the execution of tests without mocks tends to be slow. Good candidates for mocks are databases, other products, services, and so on.

Before we go deeper into mocks, let us go through reasons why one would employ them in the first place.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.230.81