Mocking Dependencies in Unit Tests with Mockito: A Java Example

In Java development, writing unit tests is a crucial part of ensuring that your code behaves as expected. One common challenge in unit testing is handling dependencies, especially when dealing with services or components that are complex to instantiate or have side effects. This is where Mockito, a popular mocking framework for Java, comes into play. In this article, we will explore how to use Mockito to mock dependencies in a unit test, using a simple example.

Why Mocking?

Mocking is the process of creating objects that simulate the behavior of real objects. In unit testing, mocks are used to isolate the code being tested from its dependencies. This isolation helps in:

1. Reducing Test Complexity: By mocking dependencies, you don’t have to set up complex environments or data states.
2. Eliminating Side Effects: Mocks ensure that tests do not have unintended interactions with databases, file systems, or other services.
3. Focusing on the Unit Under Test: It allows you to focus on the behavior of the unit of code you’re testing, rather than the behavior of its dependencies.

Example Scenario

Let’s consider a Java class named testclass that has a dependency on a service called Hello. The testclass contains a method test1() which calls the abc() method on the Hello service.

We want to write a unit test for the test1() method, but since Hello is a service, it might involve complex logic or external calls, making it hard to use in a straightforward unit test. This is where Mockito comes in.

Setting Up Mockito

First, add Mockito to your project’s dependencies. If you’re using Maven, include the following in your pom.xml:

Writing the Unit Test

In your test class, create a mock instance of Hello using the @Mock annotation. Initialize the mocks in a setup method annotated with @BeforeEach (JUnit 5) or @Before (JUnit 4). Inject the mock into your testclass instance. Here’s an example test:


Mockito provides an elegant way to handle dependencies in unit tests. It allows for writing clean, isolated tests that focus solely on the unit of code under test. By following the steps outlined in this article, Java developers can effectively mock dependencies in their unit tests, leading to more robust and maintainable code.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: