How to Write Test Cases in 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)

我这里先选择maven‑archetype‑quickstart

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 asfollows****:****

复制代码
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>5.18.0</version>
    <scope>test</scope>
</dependency>

Dependency for Junit is asfollows****:****

复制代码
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.8.2</version>
</dependency>

Below is the complete code for the pom.xml file

复制代码
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>mockito-demo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>mockito-demo</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>5.18.0</version>
      <scope>test</scope>
    </dependency>



    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>


  </dependencies>
</project>

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

复制代码
import java.util.List;

public interface TodoService {
    // Method to retrieve todos for a given user
    List<String> retrieveTodos(String user);
}

Example: Java Program to Illustrate TodoServiceImpl File

复制代码
import java.util.ArrayList;
import java.util.List;

public class TodoServiceImpl {

    private TodoService todoService;

    // Constructor
    public TodoServiceImpl(TodoService todoService) {
        this.todoService = todoService;
    }

    // Method to filter todos that contain the word "Java"
    public List<String> retrieveTodosRelatedToJava(String user) {
        List<String> filteredTodos = new ArrayList<>();
        List<String> todos = todoService.retrieveTodos(user);

        for (String todo : todos) {
            if (todo.contains("Java")) {
                filteredTodos.add(todo);
            }
        }
        return filteredTodos;
    }
}

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.javafile.

Then click on the Generatebutton.

Then click on the Test button.

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

****Example:****Java Program to Illustrate TodoServiceImplMockTest File

复制代码
package org.example;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

import java.util.Arrays;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

// Runs tests with Mockito support
@RunWith(MockitoJUnitRunner.class)
public class TodoServiceImplMockTest {

    private TodoServiceImpl todoBusiness;

    // Mock object for TodoService
    @Mock
    private TodoService todoServiceMock;

    // Runs before each test
    @Before
    public void setUp() {
        todoBusiness = new TodoServiceImpl(todoServiceMock);
    }

    // Test case: when todos contain "Java"
    @Test
    public void testRetrieveTodosRelatedToJava_usingMock() {
        List<String> todos = Arrays.asList("Learn Spring", "Learn Java", "Learn Spring Boot");
        when(todoServiceMock.retrieveTodos("User")).thenReturn(todos);

        List<String> filteredTodos = todoBusiness.retrieveTodosRelatedToJava("User");
        assertEquals(1, filteredTodos.size()); // Only "Learn Java" matches
    }

    // Test case: when todos list is empty
    @Test
    public void testRetrieveTodosRelatedToJava_withEmptyList_usingMock() {
        List<String> todos = Arrays.asList();
        when(todoServiceMock.retrieveTodos("Dummy")).thenReturn(todos);

        List<String> filteredTodos = todoBusiness.retrieveTodosRelatedToJava("Dummy");
        assertEquals(0, filteredTodos.size());
    }
}

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).

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

相关推荐
测试修炼手册4 小时前
[测试技术] TestNG 入门与实战:分组、数据驱动与并行执行
junit·单元测试·log4j
START_GAME6 小时前
LuaTools的使用指南
junit
测试修炼手册1 天前
[测试技术] JUnit 6 入门与实战:断言、参数化与 Mockito
数据库·junit·sqlserver
大黄说说5 天前
Hyperf 协程 PHP 实战:高并发秒杀接口从 0 到 1 落地
junit
名字还没想好☜8 天前
用 Redis + Redisson 实现分布式锁:从踩坑到生产可用
java·redis·分布式·junit·分布式锁·redisson
ipad协议源码8 天前
为何网站会出现的挂马?
junit·软件开发·开源源码
再玩一会儿看代码9 天前
JUnit 测试框架详解:从实际开发、业务测试到 Java 面试高频问题
java·经验分享·笔记·junit·面试
童话的守望者10 天前
BookHub (RWCTF 2018) 通关
junit
techdashen13 天前
Uber 如何完成超大规模 JUnit 迁移:从 JUnit 4 到 JUnit 5 的自动化工程实践
junit·sqlserver·自动化
会周易的程序员15 天前
使用 LuaBridge 封装 C++ 日志库 microLog 为 Lua 模块
c++·物联网·junit·lua·日志·iot·aiot