SpringBoot对shiro进行mock单元测试

  • 当前案例环境

    junit-5、Spring5.0.x、Spring Boot 2.0.x

  • shiro单元测试主要知识点

    Shiro中的ThreadContext.bind(securityManager)只绑定了所有SecurityManger,而SecurityManager下包含多个Subject,将ThreadContext.bind(securityManager)改为ThreadContext.bind(subject)即可以指定subject身份去测试接口。

  • 权限测试接口:

@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);
  • 测试案例:

@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登录后权限处理、同号只能单处登录、登出后权限处理功能的结果):

测试结果图

你可能感兴趣的:(SpringBoot对shiro进行mock单元测试)