springboot对shiro进行mock单元测试

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

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

  1. @ApiOperation("[可接入]分页查询管理员")
  2. @ApiResponses({@ApiResponse(code = 200, message = "访问成功", response = APIResponse.class),
  3. @ApiResponse(code = 201, message = "data", response = BackPageManagerDTO.class)})
  4. @ApiImplicitParams({@ApiImplicitParam(name = "page", value = "页码", required = true, defaultValue = "1"),
  5. @ApiImplicitParam(name = "size", value = "数目", required = true, defaultValue = "15")})
  6. @GetMapping("/page")
  7. @RequiresPermissions(PermissionConst.MANAGER)
  8. 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身份去测试接口。个人案例如下:

  1. @SpringBootTest(classes = BackendApplication.class)
  2. @AutoConfigureMockMvc
  3. @SpringJUnitConfig
  4. @PropertySource(value = "classpath:jdbc.properties", encoding = "UTF-8")
  5. @ImportResource(locations = {"classpath:*-config.xml"})
  6. @WebAppConfiguration
  7. class ManagerTest {
  8. @Resource
  9. private BackManagerController managerController;
  10. @Resource
  11. private SecurityManager securityManager;
  12. @Resource
  13. private WebApplicationContext webApplicationContext;
  14. @Resource
  15. private SessionDAO sessionDAO;
  16. private Subject subject;
  17. private MockMvc mockMvc;
  18. private MockHttpServletRequest mockHttpServletRequest;
  19. private MockHttpServletResponse mockHttpServletResponse;
  20. private void login(String username, String password) {
  21. subject = new WebSubject.Builder(mockHttpServletRequest, mockHttpServletResponse)
  22. .buildWebSubject();
  23. UsernamePasswordToken token = new UsernamePasswordToken(username, password, true);
  24. subject.login(token);
  25. ThreadContext.bind(subject);
  26. }
  27. @BeforeEach
  28. void before() {
  29. mockHttpServletRequest = new MockHttpServletRequest(webApplicationContext.getServletContext());
  30. mockHttpServletResponse = new MockHttpServletResponse();
  31. MockHttpSession mockHttpSession = new MockHttpSession(webApplicationContext.getServletContext());
  32. mockHttpServletRequest.setSession(mockHttpSession);
  33. SecurityUtils.setSecurityManager(securityManager);
  34. mockMvc = MockMvcBuilders
  35. .webAppContextSetup(webApplicationContext)
  36. .build();
  37. login("test112", "111111");
  38. }
  39. @Test
  40. void page() throws Exception {
  41. System.out.println("-------------shiro基本权限测试-------------");
  42. System.out.println("init page result:" +
  43. mockMvc.perform(MockMvcRequestBuilders.get("/back/manager/page?page=1&size=15"))
  44. .andExpect(MockMvcResultMatchers.status().isOk())
  45. .andReturn()
  46. .getResponse()
  47. .getContentAsString());
  48. System.err.println("all session id:" +
  49. sessionDAO.getActiveSessions().stream()
  50. .map(Session::getId)
  51. .reduce((x, y) -> x + "," + y)
  52. .orElse(""));
  53. System.out.println("-------------测试同一用户异地登录将另一session踢出,该过程在CredentialsMatcher进行处理-------------");
  54. login("test112", "111111");
  55. System.out.println("user login again page result:" +
  56. mockMvc.perform(MockMvcRequestBuilders.get("/back/manager/page?page=1&size=15"))
  57. .andExpect(MockMvcResultMatchers.status().isOk())
  58. .andReturn()
  59. .getResponse()
  60. .getContentAsString());
  61. System.err.println("all session id:" +
  62. sessionDAO.getActiveSessions().stream()
  63. .map(Session::getId)
  64. .reduce((x, y) -> x + "," + y)
  65. .orElse(""));
  66. System.out.println("-------------测试登出后权限-------------");
  67. subject.logout();
  68. System.out.println("logout page result:" + mockMvc.perform(MockMvcRequestBuilders.get("/back/manager/page?page=1&size=15"))
  69. .andExpect(MockMvcResultMatchers.status().isOk())
  70. .andReturn()
  71. .getResponse()
  72. .getContentAsString());
  73. }
  74. }

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

原文地址:https://blog.csdn.net/z28126308/article/details/81034769
原文地址:https://www.cnblogs.com/jpfss/p/11171715.html