Simplifying Testing using a Mock Tool

Let's learn to simplify tests using the Mock tool.

Transforming stub into mock

Let’s consider how to transform our smart stub into a mock. To do so would involve:

  • Trapping and storing the parameters passed to the get() method.
  • Supporting the ability to verify upon test completion that the stored parameters to get() contains the expect parameters.

Creating a mock that performs those steps may seem like overkill. What does it get us? Actually, not much at all. If we were to write a second or third test that used the same mock, though, we’d shrink the amount of code we need to write for each.

If we create more mock implementations for other troublesome dependencies, we will likely find a way to refactor the redundancy between them. We end up with a general-purpose tool that allows us to quickly bang out tests employing mocks. Our tests will be smaller and more concisely declare what they’re trying to prove.

Mockito

Rather than reinvent the wheel, we instead should use the fruits of someone else’s labor who’s done the work of designing a general-purpose mock tool. Mockito is just such a tool.

Setting up Mockito is a matter of downloading some JARs and configuring our project to point to them. Once it’s set up, the tests we write that use Mockito should statically import everything in org.mockito.Mockito. Here’s a complete test that uses Mockito (including the import statement):

Get hands-on with 1200+ tech skills courses.