测试类如何编写?如何用Mock数据避免影响到数据库的内容?

发布于:2025-05-10 ⋅ 阅读:(11) ⋅ 点赞:(0)


欢迎来到 Shane 的博客~

心有猛虎,细嗅蔷薇。

前言

在学习代码的时候,发现其实测试是一个技术活,尤其是在Java中编写JUnit测试样例,但是有时候又不想影响到数据库的内容,比如删除添加操作。这些都可以通过JUnit+Mockito来实现。

过程

  1. 添加依赖
<dependencies>
    <!-- JUnit 5 依赖 -->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.8.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.8.2</version>
        <scope>test</scope>
    </dependency>
    <!-- Mockito 依赖 -->
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>4.0.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>
  1. 如果是spring项目需要注入服务需要为Test类加上@SpringTest注解
  2. 假设我现在需要验证一下根据查询数据库的对象的方法是否生效,那么可以先编写一个触发条件,使用Mock
    首先是注入Mapper仓库(要加上MockBean注解)\
 @MockBean
 private ParentingEncyclopediaMapper parentingEncyclopediaMapper;


接着是模拟触发搜索的行为

// 设置模拟对象的行为,当调用 selectById 方法且参数为 1 时,返回测试用的对象
when(parentingEncyclopediaMapper.selectById(1L)).thenReturn(testEncyclopedia);
  1. 设置断点点击调试查看每一步是否在自己的预判内,也可以使用assert

代码示例

package com.shane.mcp;

import com.shane.mcp.mapper.ParentingEncyclopediaMapper;
import com.shane.mcp.model.entity.ParentingEncyclopedia;
import com.shane.mcp.service.ParentingEncyclopediaService;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;

import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;

@SpringBootTest // 需要加上注解才能注入
class ParentingEncyclopediaServiceTest {
    @Resource
    private ParentingEncyclopediaService parentingEncyclopediaService;

    @MockBean
    private ParentingEncyclopediaMapper parentingEncyclopediaMapper;

    @Test
    void testGetEncyclopediaById() {
        // 创建一个测试用的 ParentingEncyclopedia 对象
        ParentingEncyclopedia testEncyclopedia = new ParentingEncyclopedia();
        testEncyclopedia.setId(1L);
        testEncyclopedia.setTitle("Test Title");
        testEncyclopedia.setContext("Test Context");

        // 设置模拟对象的行为,当调用 selectById 方法且参数为 1 时,返回测试用的对象
        when(parentingEncyclopediaMapper.selectById(1L)).thenReturn(testEncyclopedia);

        // 调用要测试的方法
        ParentingEncyclopedia result = parentingEncyclopediaService.findParentingEncyclopediaById(1L);
        // 这个逻辑链就是测试的方法势必会调用selectById的方法,通过设置触发selectById返回对象,来判断是否触发,达到测试的目的
        // 验证结果
        assertEquals(testEncyclopedia, result);
    }
 }

总结

编写测试类是一个好习惯,Junit和Mockito是很棒的一个组合。

END!


网站公告

今日签到

点亮在社区的每一天
去签到