springboot对shiro进行mock单元测试

  环境:junit-5、Spring5.0.x、Spring Boot 2.0.x

    以下是用来权限测试的接口:

@ApiOperation("[可接入]分页查询管理员")
@ApiResponses({@ApiResponse(code = 200, message = "访问成功", response = APIResponse.class),
        @ApiResponse(code = 201, message = "data", response = BackPageManagerDTO.class)})
@ApiImplicitParams({@ApiImplicitParam(name = "page", value = "页码", required = true, defaultValue = "1"),
        @ApiImplicitParam(name = "size", value = "数目", required = true, defaultValue = "15")})
@GetMapping("/page")
@RequiresPermissions(PermissionConst.MANAGER)
APIResponse page(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "15") Integer size);

    百度shiro的单元测试,发现没有一个是可以在测试时以指定Subject运行的,最接近的是ThreadContext.bind(securityManager),但这只是绑定了所有SecurityManger,而SecurityManager下还有很多Subject,将ThreadContext.bind(securityManager)改为ThreadContext.bind(subject)即可以指定subject身份去测试接口。个人案例如下:

 

@SpringBootTest(classes = BackendApplication.class)
@AutoConfigureMockMvc
@SpringJUnitConfig
@PropertySource(value = "classpath:jdbc.properties", encoding = "UTF-8")
@ImportResource(locations = {"classpath:*-config.xml"})
@WebAppConfiguration
class ManagerTest {
    @Resource
    private BackManagerController managerController;
    @Resource
    private SecurityManager securityManager;
    @Resource
    private WebApplicationContext webApplicationContext;
    @Resource
    private SessionDAO sessionDAO;
    private Subject subject;
    private MockMvc mockMvc;
    private MockHttpServletRequest mockHttpServletRequest;
    private MockHttpServletResponse mockHttpServletResponse;
 
 
    private void login(String username, String password) {
        subject = new WebSubject.Builder(mockHttpServletRequest, mockHttpServletResponse)
                .buildWebSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, true);
        subject.login(token);
        ThreadContext.bind(subject);
    }
 
    @BeforeEach
    void before() {
        mockHttpServletRequest = new MockHttpServletRequest(webApplicationContext.getServletContext());
        mockHttpServletResponse = new MockHttpServletResponse();
        MockHttpSession mockHttpSession = new MockHttpSession(webApplicationContext.getServletContext());
        mockHttpServletRequest.setSession(mockHttpSession);
        SecurityUtils.setSecurityManager(securityManager);
        mockMvc = MockMvcBuilders
                .webAppContextSetup(webApplicationContext)
                .build();
        login("test112", "111111");
    }
 
    @Test
    void page() throws Exception {
        System.out.println("-------------shiro基本权限测试-------------");
        System.out.println("init page result:" +
                mockMvc.perform(MockMvcRequestBuilders.get("/back/manager/page?page=1&size=15"))
                        .andExpect(MockMvcResultMatchers.status().isOk())
                        .andReturn()
                        .getResponse()
                        .getContentAsString());
        System.err.println("all session id:" +
                sessionDAO.getActiveSessions().stream()
                        .map(Session::getId)
                        .reduce((x, y) -> x + "," + y)
                        .orElse(""));
        System.out.println("-------------测试同一用户异地登录将另一session踢出,该过程在CredentialsMatcher进行处理-------------");
        login("test112", "111111");
        System.out.println("user login again page result:" +
                mockMvc.perform(MockMvcRequestBuilders.get("/back/manager/page?page=1&size=15"))
                        .andExpect(MockMvcResultMatchers.status().isOk())
                        .andReturn()
                        .getResponse()
                        .getContentAsString());
        System.err.println("all session id:" +
                sessionDAO.getActiveSessions().stream()
                        .map(Session::getId)
                        .reduce((x, y) -> x + "," + y)
                        .orElse(""));
        System.out.println("-------------测试登出后权限-------------");
        subject.logout();
        System.out.println("logout page result:" + mockMvc.perform(MockMvcRequestBuilders.get("/back/manager/page?page=1&size=15"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn()
                .getResponse()
                .getContentAsString());
    }
}

测试结果图(以下测试结果分别是测shiro登录后权限处理、同号只能单处登录、登出后权限处理功能的结果):

原文地址:https://blog.csdn.net/z28126308/article/details/81034769
posted @   星朝  阅读(2320)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2018-07-11 理解HTTP幂等性
2018-07-11 关于高并发系统数据幂等的常用技术解决方案
2018-07-11 高并发的核心技术-幂等的实现方案
2018-07-11 RPC服务和HTTP服务对比
2018-07-11 一个虐你千百遍的问题:“RPC好,还是RESTful好?”
2018-07-11 RPC原理及RPC实例分析
2018-07-11 Centos下Elasticsearch安装详细教程
点击右上角即可分享
微信分享提示