SpringBoot 登录接口单元测试(Shiro方式)

SpringBoot 登录接口单元测试

1.针对登录接口获取Token

package com.demo.test.controller;

import com.alibaba.fastjson.JSONObject;
import com.demo.test.Application;
import com.demo.test.req.auth.LoginReq;
import com.demo.test.resp.auth.UserResp;
import org.apache.shiro.SecurityUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.Filter;

import java.io.File;
import java.io.RandomAccessFile;

import static com.demo.test.TokenTest.*;
import static com.deno.test.enums.ResultCode.SUCCESS_RESP;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * 登录接口测试
 *
 * @author earl
 **/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
@Transactional
public class AuthorityControllerTest {

    private MockMvc mockMvc;
    private MockHttpServletRequest mockHttpServletRequest;

    @Autowired
    WebApplicationContext webApplicationContext;

    @Autowired
    private org.apache.shiro.mgt.SecurityManager securityManager;

    @Before
    public void before()   {
        DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(webApplicationContext);
        //构造shiro过滤器,这个名字对应项目shiro配置的bean
        builder.addFilters((Filter) webApplicationContext.getBean("shirFilter"));
        mockMvc = builder.build();
        //初始化shiro环境,因为代码用了shiro的线程上下文环境
        mockHttpServletRequest = new MockHttpServletRequest(webApplicationContext.getServletContext());
        MockHttpSession mockHttpSession = new MockHttpSession(webApplicationContext.getServletContext());
        mockHttpServletRequest.setSession(mockHttpSession);
        SecurityUtils.setSecurityManager(  securityManager);

    }


    @Test
    public void loginSuccessTest() throws Exception {
        LoginReq req = new LoginReq();
        req.setUserName("test");
        req.setPassword("123456");
        req.setRememberMe(0);
        String responseJson = mockMvc.perform( MockMvcRequestBuilders.post("/login")
                .contentType(MediaType.APPLICATION_JSON_UTF8).header(TOKEN_KEY ,  TOKEN_VALUE).header("language","ZH")
                .content(JSONObject.toJSONString(req)))
                .andExpect(status().isOk()).andDo(MockMvcResultHandlers.print()) .andReturn().getResponse().getContentAsString();
        JSONObject json = JSONObject.parseObject(responseJson);
        String resultCode =  json.getString("code");
        Assert.assertEquals(resultCode, SUCCESS_RESP.getCode());

        UserResp userResp =  JSONObject.toJavaObject(json.getJSONObject("data"), UserResp.class);
        Assert.assertNotNull(userResp );
        Assert.assertNotNull(userResp.getToken() );

        //写入到本地的环境中
        File file = new File(TOKEN_PATH);
        if(!file.exists()) {
            file.mkdirs();
        }
        RandomAccessFile tokenFile = new RandomAccessFile(TOKEN_FILE, "rw");
        tokenFile.writeUTF(userResp.getToken());
    }




}

直接在其他接口引用TokenTest的静态变量即可

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 测试token
 *
 * @author earl
 **/
public final class TokenTest {

    private TokenTest(){}

    public static final String TOKEN_KEY = "token";
    public static final String TOKEN_PATH = "D:\\webdatas\\data\\";
    public static final String TOKEN_FILE = TOKEN_PATH+"token.txt";
    public static String TOKEN_VALUE ;

    static {
        try {
            RandomAccessFile file = new RandomAccessFile(TOKEN_FILE,"r"  );
            TOKEN_VALUE =  file.readUTF();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

  

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值