VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-write-test-cases-in-java-application-using-mockito-and-junit/

⇱ How to Write Test Cases in Java Application using Mockito and Junit? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Write Test Cases in Java Application using Mockito and Junit?

Last Updated : 29 Sep, 2025

Unit testing is an essential practice in software development that ensures individual components of an application work as expected.

  • Mockito:Mockito is an open-source testing framework used to mock dependencies and isolate the class under test. This makes unit tests easier to write, understand and maintain.
  • JUnit:JUnit is a standard testing framework for Java applications. Together, JUnit and Mockito provide a combination for writing unit tests.

In this article, we will learn step by step how to write unit test cases for a Java application using Mockito and JUnit.

Step-by-Step Implementation

Step 1: Create a Maven Project

Create a Maven project in your favorite Java IDE (Here we are using IntelliJ IDEA)

👁 Image

Step 2: Add Dependencies

When you have successfully created a Maven project you have to add some dependencies in your pom.xml file. We have to add the following dependency in your pom.xml file.

Dependency for Mockito is as follows:

Dependency for Junit is as follows:

Below is the complete code for the pom.xml file

Step 3: Create the Service and Implementation Classes

Now you have to create one interface named as TodoService and one class named as TodoServiceImpl. 

Example: Java Program to Illustrate TodoService File

Example: Java Program to Illustrate TodoServiceImpl File

Step 4: Write Unit Tests with Mockito and JUnit

Now we are going to perform unit testing for the retrieveTodosRelatedToJava() method that is present inside the TodoServiceImpl.java file. To create the test class follow these steps. At first Right-click inside the TodoServiceImpl.java file. 

Then click on the Generate button.

👁 Image

Then click on the Test button.

👁 Image

A pop-up window will be shown like this. Here you can modify your test class name. Also, check the setUp and the method that you want to perform unit testing. 

👁 Image

Example: Java Program to Illustrate TodoServiceImplMockTest File

Step 5: Run the Tests

  • Right-click on the test class (TodoServiceImplMockTest).
  • Select Run 'TodoServiceImplMockTest'.
  • You will see both test cases pass (green check marks).

👁 Image

Comment
Article Tags:
Article Tags: