在有安全验证的情况下做单元测试Test

版本信息


<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.14.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>1.5.14.RELEASE</version>
<!--实际里面spring-security-web的版本是4.2.7-->
</dependency>

添加依赖

<!--spring-security单元测试-->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>4.2.3.RELEASE</version>
<scope>test</scope>
</dependency>
<!--spring-security单元测试-->

需求

  1. 在写单元测试时,需要模拟某个用户的登录状态
  2. 在写单元测试时,需要模拟某个用户具有某个权限,但又不想改变数据库
  3. 编写单元测试时,需求完整调用某个用户的登录

解决需求:

springSecurity提供了相关的组件spring-security-test,可参考官方文档(https://docs.spring.io/spring-security/site/docs/5.0.6.RELEASE/reference/htmlsingle/#test-method-withmockuser),该组件提供了相关的注解来来模拟用户登录信息或者调用用户登录的方法

  • @WithMockUser 模拟用户,手动指定用户名和授权
  • @WithAnonymousUser 模拟匿名用户
  • @WithUserDetails 模拟用户,给定用户名,通过自定义UserDetails来认证
  • @WithSecurityContext 通过SecurityContext构造器模拟用户

例如

@Test
@WithMockUser(username="admin",roles={"USER","ADMIN"})
public void getMessageWithMockUserCustomUser() {
String message = messageService.getMessage();
...
}

模拟了一个名叫admin的用户,拥有角色"USER","ADMIN"

代码范例


import com.alibaba.fastjson.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext; import java.util.HashMap;
import java.util.Map; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.logout;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /**
* 接口测试+ SpringSecurity的用户登录模拟
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
@Rollback(true)// 事务自动回滚,默认是true。可以不写
public class ExampleRestClientTest { private MockMvc mockMvc; // 模拟MVC对象,通过MockMvcBuilders.webAppContextSetup(this.wac).build()初始化。 @Autowired
private WebApplicationContext wac; // 注入WebApplicationContext @Before // 在测试开始前初始化工作
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).apply(springSecurity()).build();
} @Test
@WithUserDetails(value = "admin", userDetailsServiceBeanName = "customUserDetailsService")
public void testQ1() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("param1", "valueaa"); MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/secmenu/getUserMenuList")
.contentType(MediaType.APPLICATION_JSON_UTF8).content(JSONObject.toJSONString(map)))
.andExpect(status().is(200))// 模拟向testRest发送get请求
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// 预期返回值的媒体类型text/plain;charset=UTF-8
.andReturn();// 返回执行请求的结果 } @Test
public void testFormLoginSuccess() throws Exception { // 测试登录成功
mockMvc
.perform(formLogin("/login").user("admin").password("123456"))
.andExpect(authenticated());
} @Test
public void testFormLoginFail() throws Exception {
// 测试登录失败
mockMvc
.perform(formLogin("/login").user("admin").password("invalid"))
.andExpect(unauthenticated());
} @Test
public void testLogoutFail() throws Exception {
// 测试退出登录
mockMvc.perform(logout("/logout")).andExpect(unauthenticated());
}
}

完整项目工程参考

https://github.com/starmoon1994/springsecurity-collection

2539-SpringSecurity系列--在有安全验证的情况下做单元测试Test的更多相关文章

  1. 关于JDBC技术中,调用MySQL中不建议在没有服务器身份验证的情况下建立SSL连接错误解决

    今天学习到了JBDC前沿:对JDBC编写步骤的封装,出现了一大串红色报错(当然,也不能叫报错,毕竟不是所有的红色都是错误eeror,) 错误如下: Establishing SSL connectio ...

  2. SpringSecurity系列之自定义登录验证成功与失败的结果处理

    一.需要自定义登录结果的场景 在我之前的文章中,做过登录验证流程的源码解析.其中比较重要的就是 当我们登录成功的时候,是由AuthenticationSuccessHandler进行登录结果处理,默认 ...

  3. AngularJs 入门系列-2 表单验证

    对于日常的开发来说,最常见的开发场景就是通过表单编辑数据,这里涉及的问题就是验证问题. angularjs 内置已经支持了常见的验证方式,可以轻松实现表单验证. 1. 绑定 为了方便,我们在 $sco ...

  4. 前端测试框架Jest系列教程 -- Expect(验证)

    写在前面 在编写测试时,我们通常需要检查值是否满足某些条件,Jest中提供的expect允许你访问很多“Matchers”,这些“匹配器”允许您验证不同的东西. Expect 可以验证什么 Jest中 ...

  5. 【FICO系列】SAP FI验证故障排除(调试)

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[FICO系列]SAP FI验证故障排除(调试) ...

  6. 【SpringSecurity系列2】基于SpringSecurity实现前后端分离无状态Rest API的权限控制原理分析

    源码传送门: https://github.com/ningzuoxin/zxning-springsecurity-demos/tree/master/01-springsecurity-state ...

  7. Spring Boot干货系列:(十二)Spring Boot使用单元测试(转)

    前言这次来介绍下Spring Boot中对单元测试的整合使用,本篇会通过以下4点来介绍,基本满足日常需求 Service层单元测试 Controller层单元测试 新断言assertThat使用 单元 ...

  8. 用SignalR 2.0开发客服系统[系列4:负载均衡的情况下使用SignalR]

    前言 交流群:195866844 目录: 用SignalR 2.0开发客服系统[系列1:实现群发通讯] 用SignalR 2.0开发客服系统[系列2:实现聊天室] 用SignalR 2.0开发客服系统 ...

  9. [js高手之路]深入浅出webpack教程系列6-插件使用之html-webpack-plugin配置(下)

    上文我们对html-webpack-plugin的实例htmlWebpackPlugin进行了遍历分析,讲解了几个常用属性( inject, minify )以及自定义属性的添加,本文,我们继续深入他 ...

随机推荐

  1. 聊一聊 HBase 是如何写入数据的?

    hi,大家好,我是大D.今天继续了解下 HBase 是如何写入数据的,然后再讲解一下一个比较经典的面试题. Region Server 寻址 HBase Client 访问 ZooKeeper: 获取 ...

  2. 20212115 实验三 《python程序设计》实验报告

    实验报告 20212115<python程序设计>实验三报告 课程:<Python程序设计>班级: 2121姓名: 朱时鸿学号:20212115实验教师:王志强老师实验日期:2 ...

  3. TornadoFx实现侧边栏菜单效果

    原文地址:TornadoFx实现侧边栏菜单效果 - Stars-One的杂货小窝 之前年前研究的东西,给蓝奏批量下载器重构了页面,实现了侧边栏菜单的效果,稍微总结下把 效果 实现 首先,要说明的是,总 ...

  4. SpringCloud Alibaba Sentinel 限流详解

    点赞再看,养成习惯,微信搜索[牧小农]关注我获取更多资讯,风里雨里,小农等你,很高兴能够成为你的朋友. 项目源码地址:公众号回复 sentinel,即可免费获取源码 熔断规则 在上一篇文章中我们讲解了 ...

  5. 前端2CSS2

    内容概要 伪元素选择器 选择器优先级 字体样式 文字属性 背景属性 display属性 边框属性 盒子模型 浮动(重要) 解决浮动造成的影响 内容详情 伪元素选择器 """ ...

  6. swap函数模板

    在许多应用程序中,都有交换相同类型的两个变量内容的需要.例如,在对整数数组进行排序时,将需要一个函数来交换两个变量的值,如下所示: void swap(int &a, int &b) ...

  7. ngx_http_fastcgi_module 的那些事

    是什么? 顾名思义,是Nginx用来处理FastCGI的模块.FastCGI是什么?这个以后再讲,可以说的是现在LNMP架构里面,PHP一般是以PHP-CGI的形式在运行,它就是一种FastCGI,我 ...

  8. Windows系统重置用户登录密码

    更新记录 2022年4月16日:本文迁移自Panda666原博客,原发布时间:2021年8月23日. 方法一.使用带有密码恢复功能的PE盘 买一张 PE光盘 或 自制PE启动盘,这里推荐微PE. 准备 ...

  9. TypeScript(4)接口

    介绍 TypeScript 的核心原则之一是对值所具有的结构进行类型检查.我们使用接口(Interfaces)来定义对象的类型.接口是对象的状态(属性)和行为(方法)的抽象(描述) 接口初探 声明接口 ...

  10. BUUCTF-菜刀666

    菜刀666 这题和之前做过的流量题不同,对我还是有些难度.看了看大佬的wp才做出来的 wireshark打开流量包,一开始只是单纯过滤http,包很多,看花了眼,看了好多也没觉得有啥异常. 后面才知道 ...