springboot对shiro进行mock单元测试
需求缘起:公司一直用swagger进行后台接口测试,但后台添加权限后利用swagger无法有效测试出shiro的配置,只能等前端接好接口后才能测出shiro的配置是否有问题,于是需要另一套测试shiro的方法。从在时间消耗与复杂度上思考要找出shiro session与swagger的集成方案感觉成本太高,于是就选择用回常见的mock test。
环境: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登录后权限处理、同号只能单处登录、登出后权限处理功能的结果):