Table of Contents

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.

Learn More about Encora

We are the software development company fiercely committed and uniquely equipped to enable companies to do what they can’t do now.

Learn More

Global Delivery

READ MORE

Careers

READ MORE

Industries

READ MORE

Related Insights

Online Travel Agencies: Some Solutions to changes in booking and commission attributions

Discover how we can simplify travel changes for both travelers and OTAs using blockchain and ...

Read More

The AI-Powered Journey: How AI is Changing the Face of Travel

As travel elevates itself into an experience where every journey is as unique as the travelers ...

Read More

Enhancing Operational Excellence with AI: A Game-Changer for the Hospitality Industry

By AI, the hospitality industry can offer the best of both worlds: the efficiency and ...

Read More
Previous Previous
Next

Accelerate Your Path
to Market Leadership 

Encora logo

Santa Clara, CA

+1 669-236-2674

letstalk@encora.com

Innovation Acceleration

Speak With an Expert

Encora logo

Santa Clara, CA

+1 (480) 991 3635

letstalk@encora.com

Innovation Acceleration