SpringBoo项目标准测试样例

文章目录

    • 概要
    • Controller Api 测试
      • 源码
      • 单元测试
      • 集成测试

概要

Spring Boot项目测试用例

测试方式是否调用数据库使用的注解特点
单元测试(Mock Service)❌ 不调用数据库@WebMvcTest + @MockBean只测试 Controller 逻辑,速度快
集成测试(真实数据库)✅ 调用数据库@SpringBootTest真实保存数据,确保数据库逻辑正确

Controller Api 测试

Restful Api

源码

package cn.star.framework.example.controller;import cn.star.framework.controller.AbstractController;
import cn.star.framework.core.api.AppResult;
import cn.star.framework.core.api.Pageable;
import cn.star.framework.example.entity.Example;
import cn.star.framework.example.service.ExampleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** ExampleController<br>** @author zhaoweiping*     <p style='color: red'>Created on 2025-02-06 16:16:40* @since 3.0.0*/
@RestController
@RequestMapping(value = "/example")
@Api(tags = "框架测试")
public class ExampleController extends AbstractController<Example, String> {@Autowired @Getter private ExampleService service;@Override@PostMapping@ApiOperation(value = "新增")public AppResult<Example> save(@RequestBody Example entity) {return super.save(entity);}@Override@PutMapping@ApiOperation(value = "更新")public AppResult<Example> update(@RequestBody Example entity) {return super.update(entity);}@Override@DeleteMapping@ApiOperation(value = "删除")public AppResult<List<Example>> deleteByIds(@RequestBody String... ids) {return super.deleteByIds(ids);}@GetMapping@ApiOperation(value = "查询(列表)")public AppResult<List<Example>> list(HttpServletRequest request) {return super.list(request, Example.class);}@Override@GetMapping("/{id}")@ApiOperation(value = "查询(主键)")public AppResult<Example> get(@PathVariable(value = "id") String id) {return super.get(id);}@GetMapping("/page")@ApiOperation(value = "查询(分页)")public AppResult<Pageable<Example>> pageable(HttpServletRequest request) {return super.pageable(request, Example.class);}
}

单元测试

package cn.star.framework.example.controller;import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;import cn.hutool.json.JSONUtil;
import cn.star.framework.example.entity.Example;
import cn.star.framework.example.service.ExampleService;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;/*** 单元测试<br>** @author zhaoweiping*     <p style='color: red'>Created on 2025-02-06 18:52:28* @since 3.0.0*/
@Slf4j
@RunWith(SpringRunner.class)
@WebMvcTest(ExampleController.class)
public class ExampleControllerMockTest {@Autowired private MockMvc mockMvc;@MockBean private ExampleService exampleService;@Beforepublic void setup() {log.info("setup ...");}@Testpublic void save() throws Exception {Example example = new Example("1", "新增");// 不会调用真实数据库操作when(exampleService.save(Mockito.any(Example.class))).thenReturn(example);mockMvc.perform(post("/example").contentType(MediaType.APPLICATION_JSON).content(JSONUtil.toJsonStr(example)))// 断言.andExpect(status().isOk())// 打印结果.andDo(System.out::println).andDo(result -> System.out.println(result.getResponse().getContentAsString()));}
}

集成测试

package cn.star.framework.example.controller;import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;import cn.hutool.json.JSONUtil;
import cn.star.framework.core.Constant;
import cn.star.framework.example.entity.Example;
import cn.star.framework.example.service.ExampleService;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;/*** 集成测试<br>** @author zhaoweiping*     <p style='color: red'>Created on 2025-02-06 18:52:28* @since 3.0.0*/
@Slf4j
@RunWith(SpringRunner.class)
@EntityScan(basePackages = Constant.BASE_PACKAGE)
@EnableJpaRepositories(basePackages = Constant.BASE_PACKAGE)
@ComponentScan(basePackages = Constant.BASE_PACKAGE)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ExampleControllerTest {@Autowired private WebApplicationContext context;@Autowired private ExampleService exampleService;/** 在集成测试中不会自动创建,需要手动初始化 */@Autowired(required = false)private MockMvc mockMvc;@Beforepublic void setup() {log.info("setup ...");mockMvc = webAppContextSetup(context).build();}@Testpublic void save() throws Exception {Example example = new Example("1", "新增");// 不会调用真实数据库操作System.out.println(exampleService);mockMvc.perform(post("/example").contentType(MediaType.APPLICATION_JSON).content(JSONUtil.toJsonStr(example)))// 断言.andExpect(status().isOk())// 打印结果.andDo(System.out::println).andDo(result -> System.out.println(result.getResponse().getContentAsString()));List<Example> examples = exampleService.findAll();System.out.println(examples);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/69367.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Unity扩展编辑器使用整理(一)

准备工作 在Unity工程中新建Editor文件夹存放编辑器脚本&#xff0c; Unity中其他的特殊文件夹可以参考官方文档链接&#xff0c;如下&#xff1a; Unity - 手册&#xff1a;保留文件夹名称参考 (unity3d.com) 一、菜单栏扩展 1.增加顶部菜单栏选项 使用MenuItem&#xff…

Vue3+codemirror6实现公式(规则)编辑器

实现截图 实现/带实现功能 插入标签 插入公式 提示补全 公式验证 公式计算 需要的依赖 "codemirror/autocomplete": "^6.18.4","codemirror/lang-javascript": "^6.2.2","codemirror/state": "^6.5.2","cod…

4.PPT:日月潭景点介绍【18】

目录 NO1、2、3、4​ NO5、6、7、8 ​ ​NO9、10、11、12 ​ 表居中或者水平/垂直居中单元格内容居中或者水平/垂直居中 NO1、2、3、4 新建一个空白演示文稿&#xff0c;命名为“PPT.pptx”&#xff08;“.pptx”为扩展名&#xff09;新建幻灯片 开始→版式“PPT_素材.doc…

开源项目介绍-词云生成

开源词云项目是一个利用开源技术生成和展示词云的工具或框架&#xff0c;广泛应用于文本分析、数据可视化等领域。以下是几个与开源词云相关的项目及其特点&#xff1a; Stylecloud Stylecloud 是一个由 Maximilianinir 创建和维护的开源项目&#xff0c;旨在通过扩展 wordclou…

Redis双写一致性(数据库与redis数据一致性)

一 什么是双写一致性&#xff1f; 当修改了数据库&#xff08;MySQL&#xff09;中的数据&#xff0c;也要同时更新缓存&#xff08;redis&#xff09;中的数据&#xff0c;缓存中的数据要和数据库中的数据保持一致 双写一致性&#xff0c;根据业务对时间上的要求&#xff0c;…

C32.【C++ Cont】静态实现双向链表及STL库的list

目录 1.知识回顾 2.静态实现演示图 3.静态实现代码 1.初始双向链表 2.头插 3.遍历链表 4.查找某个值 4.任意位置之后插入元素 5.任意位置之前插入元素 6.删除任意位置的元素 4.STL库的list 1.知识回顾 96.【C语言】数据结构之双向链表的初始化,尾插,打印和尾删 97.【C…

二级C语言题解:矩阵主、反对角线元素之和,二分法求方程根,处理字符串中 * 号

目录 一、程序填空&#x1f4dd; --- 矩阵主、反对角线元素之和 题目&#x1f4c3; 分析&#x1f9d0; 二、程序修改&#x1f6e0;️ --- 二分法求方程根 题目&#x1f4c3; 分析&#x1f9d0; 三、程序设计&#x1f4bb; --- 处理字符串中 * 号 题目&#x1f…

采用idea中的HTTP Client插件测试

1.安装插件 采用idea中的HTTP Client插件进行接口测试,好处是不用打开post/swagger等多个软件,并且可以保存测试时的参数,方便后续继续使用. 高版本(2020版本以上)的idea一般都自带这个插件,如果没有也可以单独安装. 2.使用 插件安装完成(或者如果idea自带插件),会在每个Con…

探讨如何在AS上构建webrtc(2)从sdk/android/Build.gn开始

全文七千多字&#xff0c;示例代码居多别担心&#xff0c;没有废话&#xff0c;不建议跳读。 零、梦开始的地方 要发美梦得先入睡&#xff0c;要入睡得找能躺平的地方。那么能躺平编译webrtc-android的地方在哪&#xff1f;在./src/sdk/android/Build.gn。Build.gn是Build.nin…

Linux firewalld开启日志审计功能(2)

在Firewalld防火墙中启用和配置logdenied选项&#xff0c;记录被拒绝的数据包&#xff08;等同于开启日志功能&#xff09; 效果展示&#xff1a; 1.开启日志记录功能 firewall-cmd --set-log-deniedunicast #重新加载生效配置 firewall-cmd --reload 2.配置rsyslog捕获日志…

Spring Web MVC项目的创建及使用

一、什么是Spring Web MVC&#xff1f; Spring Web MVC 是基于 Servlet API 构建的原始 Web 框架&#xff0c;从⼀开始就包含在 Spring 框架中&#xff0c;通常被称为Spring MVC。 1.1 MVC的定义 MVC 是 Model View Controller 的缩写&#xff0c;它是软件工程中的一种软件架构…

oracle:索引(B树索引,位图索引,分区索引,主键索引,唯一索引,联合索引/组合索引,函数索引)

索引通过存储列的排序值来加快对表中数据的访问速度&#xff0c;帮助数据库系统快速定位到所需数据&#xff0c;避免全表扫描 B树索引(B-Tree Index) B树索引是一种平衡树结构&#xff0c;适合处理范围查询和精确查找。它的设计目标是保持数据有序&#xff0c;并支持高效的插入…

android 适配 api 35(android 15) 遇到的问题

首先升级 targetSdkVersion 和 compileSdkVersion 到 35&#xff0c;升级后发生的报错 一、 解决方案: 升级 gradle 和 gradle 插件版本 com.android.tools.build:gradle -> 8.3.0-alpha02 gradle-wrapper.properties : distributionUrl -> gradle-8.6-bin.zip htt…

@Value属性读取系统变量错误

Value属性读取配置属性错误 场景 在测试Value读取yml配置文件属性时&#xff0c;发现系统配置属性优先级高于配置文件&#xff0c;导致注入异常值&#xff1a; 配置文件: user:name: yanxin测试类: RestController RequestMapping("/books") public class BookC…

BFS算法——广度优先搜索,探索未知的旅程(下)

文章目录 前言一. N叉树的层序遍历1.1 题目链接&#xff1a;https://leetcode.cn/problems/n-ary-tree-level-order-traversal/description/1.2 题目分析&#xff1a;1.3 思路讲解&#xff1a;1.4 代码实现&#xff1a; 二. 二叉树的锯齿形层序遍历2.1 题目链接&#xff1a;htt…

【Ubuntu】ARM交叉编译开发环境解决“没有那个文件或目录”问题

【Ubuntu】ARM交叉编译开发环境解决“没有那个文件或目录”问题 零、起因 最近在使用Ubuntu虚拟机编译ARM程序&#xff0c;解压ARM的GCC后想要启动&#xff0c;报“没有那个文件或目录”&#xff0c;但是文件确实存在&#xff0c;环境配置也检查过了没问题&#xff0c;本文记…

清理服务器/docker容器

清理服务器 服务器或docker容器清理空间。 清理conda环境 删除不用的conda虚拟环境&#xff1a; conda env remove --name python38 conda env remove --name python310清理临时目录&#xff1a;/tmp du -sh /tmp # 查看/tmp目录的大小/tmp 目录下的文件通常是可以直接删除…

康谋方案 | BEV感知技术:多相机数据采集与高精度时间同步方案

随着自动驾驶技术的快速发展&#xff0c;车辆准确感知周围环境的能力变得至关重要。BEV&#xff08;Birds-Eye-View&#xff0c;鸟瞰图&#xff09;感知技术&#xff0c;以其独特的视角和强大的数据处理能力&#xff0c;正成为自动驾驶领域的一大研究热点。 一、BEV感知技术概…

HarmonyOS 5.0应用开发——ContentSlot的使用

【高心星出品】 文章目录 ContentSlot的使用使用方法案例运行结果 完整代码 ContentSlot的使用 用于渲染并管理Native层使用C-API创建的组件同时也支持ArkTS创建的NodeContent对象。 支持混合模式开发&#xff0c;当容器是ArkTS组件&#xff0c;子组件在Native侧创建时&#…

脚本一键生成管理下游k8s集群的kubeconfig

一、场景 1.1 需要管理下游k8s集群的场景。 1.2 不希望使用默认的cluster-admin权限的config. 二、脚本 **重点参数&#xff1a; 2.1 配置变量。 1、有单独namespace的权限和集群只读权限。 2、自签名的CA证书位置要正确。 2.2 如果配置错误&#xff0c;需要重新…