springboot对shiro进行mock单元测试

springboot shiro 单元测试

进行单元测试过中发现出现这样一个异常,接口中存在认证信息,可以使用mock默认shiro 登录进行测试,
No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton. This is an invalid application configuration.

解决方式

  private MockMvc mvc;
    @Autowired
    private WebApplicationContext context;
    @Resource
    private SecurityManager securityManager;
    private Subject subject;
    private MockHttpServletRequest mockHttpServletRequest;
    private MockHttpServletResponse mockHttpServletResponse;
    private String authentication = "cbc857f882cf8a8a55b6fa5d19c5fbf2b82b1b930f0fda2de5491e54a9c189ea09bc229196ebfa00e9fe759b7acd071756d45d27caf35ac64f0c7b911209d7852eaf93d7d092b059cc6d6fd90ef5e77c1aadb934ee42613f07b17ff716b379641de2ded18ac058e540f48d490867cbc519fe4fead66fdf8be44e473089e939a6db429251f00a81db";


    @Before
    public void setUp() {
        mockHttpServletRequest = new MockHttpServletRequest(context.getServletContext());
        mockHttpServletResponse = new MockHttpServletResponse();
        MockHttpSession mockHttpSession = new MockHttpSession(context.getServletContext());
        mockHttpServletRequest.setSession(mockHttpSession);
        SecurityUtils.setSecurityManager(securityManager);

        mvc = MockMvcBuilders.webAppContextSetup(context).build();
        
        subject = new WebSubject.Builder(mockHttpServletRequest, mockHttpServletResponse)
                .buildWebSubject();
        String decryptToken = EncryptUtil.decryptToken(authentication);
        JwtToken token = new JwtToken(decryptToken);
        subject.login(token);
        ThreadContext.bind(subject);

    }

测试使用

测试获取当前登录用户的信息

    @Test
    public void getCurrentUser() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/api/v1/user/getCurrentUser"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(ResultCode.FAIL.code()))
                .andExpect(jsonPath("$.payLoad").isEmpty())
                .andReturn().getResponse().getContentAsString();
    }

你可能感兴趣的:(单元测试)