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

The Innovation vs. Maintenance Dilemma: How AI Helps Tech Companies Overcome Innovation Paralysis

Learn how AI helps tech companies overcome innovation paralysis by modernizing legacy systems ...

Read More

Engineering the Future of Hospitality: Inside Choice Hotels' Cloud Transformation Success

The partnership between Choice Hotels and Encora began with a unique perspective on organizational ...

Read More

Spatial Design Principles for Crafting Virtual Reality Learning Experiences

Effective Virtual Reality (VR) learning experiences are immersive, engaging and impactful. ...

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