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

Enabling Transformation in Hospitality through Technology-Led Innovation

As the exclusive sponsor of the 2024 Hotel Visionary Awards, we support organizations leading ...

Read More

Key Insights from HLTH 2024: The Future of Patient-Centered Healthcare

Discover key insights from HLTH 2024 on digital health, AI in diagnostics, data interoperability, ...

Read More

Data-Driven Engineering: Transforming Operations and Products from Insight to Impact

Discover how data-driven engineering transforms operations and product development, enhancing team ...

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