Annotation Magic with Mockito: Mock and Spy

Testing can be a tedious task, but Mockito makes easier by allowing you to mock objects in an simpler way. This is the second post on this topic; you can find the first Mockito post here.

If you are into learning this awesome Android testing library keep on reading.

@Mock Annotation

@Mock is the most popular used annotation of the ones provided by Mockito. We can use it to create and inject mocked instances without having to call Mockito.mock manually.

For example, here we are generating a mocked ArrayList the manual way and filling it with a single item (a size 50) and then verifying its creation,

Now lets try this another way using the @Mock annotation,

@Spy Annotation

This annotation is used to call all the normal methods of an object while still tracking every possible interaction similar to a normal object.

In this case there are also two ways of doing it. Calling the Mockito.spy,

Or using the @Spy annotation,

A Friendly Reminder

In order to enable Mockito annotation (such as @Spy, @Mock, @InjectMocks … ), we need to do one of the following,
Call the method MockitoAnnotations.initMocks(this) to initialize annotated fields
Use the built-in runner @RunWith(MockitoJUnitRunner.class)

Finally …

Basically these two annotations allow you to generate a new object with the same methods as the original. It also let's you use them to test their proper functionality without needing to instantiate them directly and saving memory in the process.

Share this post

Table of Contents