You are currently viewing Mastering Unit Testing with Mockito in Java

Mastering Unit Testing with Mockito in Java


Unit testing is a crucial aspect of software development, allowing developers to verify that individual units of code perform as expected. Mockito is a powerful framework for Java that enables effective unit testing by providing mechanisms to create mock objects, stub methods, and verify interactions between objects. In this guide, we will delve into mastering unit testing with Mockito, covering all annotations and functions with detailed examples for each.

Understanding Mockito Annotations


The @Mock annotation is used to create a mock object. It initializes a mock for the annotated field, allowing you to simulate the behavior of real objects in your tests.



The @Spy annotation is used to create a spy object, which is a partial mock of a real object. It allows you to retain the original behavior of the object while selectively stubbing or verifying certain methods.



The @InjectMocks annotation is used to inject mocks into the fields of a test class. It automatically injects mock or spy dependencies into the fields annotated with @Mock or @Spy.


Exploring Mockito Functions

Stubbing Methods

Mockito provides the when() function to stub methods of mock objects. It allows you to define the behavior of a method when it is called during testing.


Verifying Method Calls

The verify() function is used to verify that a method of a mock object has been called with specific arguments and a specific number of times.


Capturing Arguments

Mockito provides the ArgumentCaptor class to capture arguments passed to mocked methods. It allows you to verify the values of arguments passed during method calls.


3. Examples of Mockito Usage

Example: Testing a Service with Mockito

Example: Verifying Method Invocation

when() with thenReturn():

doReturn() with thenReturn():

doThrow() with thenThrow():


doAnswer() with thenAnswer():


These examples demonstrate how to use Mockito’s when(), doReturn(), doThrow(), doNothing(), doAnswer(), thenReturn(), thenThrow(), thenAnswer(), and spy() functions to define behavior for mock objects and spy objects in unit tests.


In this guide, we have covered the essential Mockito annotations and functions for mastering unit testing in Java. By understanding and utilizing these features effectively, you can write comprehensive unit tests that verify the behavior of your code and ensure its correctness and reliability. Practice and experimentation with Mockito will further enhance your proficiency in unit testing Java applications.

Leave a Reply