当前位置: 首页 > news >正文

关于 SpringBootTest 你必须知道的 - 登录认证在 Spring Boot 上的标准单元测试写法,看一眼就会怀孕。

👉 请投票支持这款 全新设计的脚手架 ,让 Java 再次伟大!

在这里插入图片描述

不要使用 @SpringBootTest

使用 @SpringBootTest 进行单元测试会启动整个 Spring Boot 容器,并引入整个项目的 development&test 依赖。缺点是速度慢、体积大、测试目标不明确、低内聚高耦合。

明确我们要测试的目标是登录功能,所以只要启动 Spring Mvc 的依赖范围就可以了,其他层面的依赖可以用「打桩」来解决。

使用 @WebMvcTest

所以只需要隔离启动 Spring Mvc 环境,即可完成登录功能的测试了。

@WebMvcTest(value = {SignController.class})
@Import({HttpFireWallConfig.class})
class SignMvcTest {@MockBean private SignService signService;@MockBean private CookieJwt cookieJwt;@Autowired private MockMvc mockMvc;@Test@WithMockUservoid signIn_givenValidHttpRequest_shouldSucceedWith200() throws Exception {String stubUsername = "test_04cb017e1fe6";String stubPassword = "test_567472858b8c";SignInDto signInDto = new SignInDto();signInDto.setUsername(stubUsername);signInDto.setPassword(stubPassword);when(signService.signIn(signInDto)).thenReturn(1L);mockMvc.perform(post("/auth/sign-in").contentType(MediaType.APPLICATION_JSON).content("""{"username": "test_04cb017e1fe6","password": "test_567472858b8c"}""").with(csrf())).andExpect(status().isOk());}@Test@WithMockUservoid signIn_givenInValidHttpRequest_shouldFailedWith400() throws Exception {String stubUsername = "test_04cb017e1fe6";String stubPassword = "test_567472858b8c";SignInDto signInDto = new SignInDto();signInDto.setUsername(stubUsername);signInDto.setPassword(stubPassword);when(signService.signIn(signInDto)).thenReturn(1L);mockMvc.perform(post("/auth/sign-in").contentType(MediaType.APPLICATION_FORM_URLENCODED).content("""{"username": "test_04cb017e1fe6","password": "test_567472858b8c"}""").with(csrf())).andExpect(status().isBadRequest());when(signService.signIn(signInDto)).thenReturn(1L);mockMvc.perform(post("/auth/sign-in").contentType(MediaType.APPLICATION_JSON).content("""{"username": "test_04cb017e1fe6"}""").with(csrf())).andExpect(status().isBadRequest());}
}

更多单元测试的写法

更多的区分了隔离环境的单元测试代码,都集成到了下面的项目中:👇
一款全新设计的脚手架 ,让 Java 再次伟大!
在这里插入图片描述


http://www.mrgr.cn/news/55247.html

相关文章:

  • 【常见大模型API调用】第二篇:阿里巴巴--通义千问
  • GRPC 压缩算法
  • 戴尔电脑win11找不到D盘的解决办法
  • 2024系统分析师考试---论区块链技术及其应用
  • 【OD】【E卷】【真题】【100分】选修课(PythonJavaJavaScriptC++C)
  • 【RoadRunner】自动驾驶模拟3D场景构建 | 自定义交叉口工具详解
  • c语言基础程序——经典100道实例。
  • On-Device Training Under 256KB Memory 端侧极端算力设备资源下的模型训练工作研究
  • 使用mvn命令导出依赖包
  • @Component 和 @Bean 的区别与联系
  • C++ 异步执行任务async()(补充)
  • 基于Java+SpringBoot+Vue的IT技术交流和分享平台
  • Linux中部署Mysql保姆级教程
  • Django中的ModelForm组件
  • 自动求导实现
  • C++ 新特性 | C++ 11 | tuple 模版
  • 跟风考的PMP帮我拿到了offer
  • Unity3D功耗和发热分析与优化详解
  • Android中使用bottomnavigation实现底部导航栏
  • CST软件如何验证“平面波+探针”的频域结果
  • 怎么用六西格玛增强解决问题的逻辑性?
  • ATTCK 框架讲解
  • 建议使用requestAnimationFrame替代定时器setInterval、setTimeout完成页面动画
  • SAP MDG —— MDG on S/4HANA 2023 FPS02 创新汇总 AI功能首次发布!
  • 七天入门LLM大模型 |提示词工程-Prompt Engineering
  • Django