SpringBoot单元测试携带Cookie

由于我SpringBoot项目,集成了SpringSecurity,而Security框架使用Redis存储Session,所以,这里列出几个关键的类

org.springframework.session.data.redis.RedisIndexedSessionRepository:解析请求携带的Cookie的Repository类
org.springframework.session.web.http.DefaultCookieSerializer:默认提取Cookie序列化的类;org.springframework.session.web.http.DefaultCookieSerializer#readCookieValues看这个方法,就能看出解析的是 Cookie Header

 

 

 

这是使用示例:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)  //这里是说明:以随机端口进行服务器的完整启动(这样请求就会经过过滤器、拦截器等前置处理)
@Slf4j
class UploadFileApiControllerTest {

    @Resource
    private TestRestTemplate testRestTemplate;

    private HttpHeaders headers;

    private List<String> cookies;

    @BeforeEach
    void login() throws Exception {

        ResponseEntity<String> exchange = testRestTemplate.exchange("/user/login", HttpMethod.POST, new HttpEntity<>("{json内容}"), String.class);
        System.out.println(exchange.getBody());

        headers = exchange.getHeaders();
        cookies = exchange.getHeaders().get("Set-Cookie");

    }


    @Test
    void initializedUploadFileInfo() throws Exception {


        File file = ResourceUtils.getFile("classpath:TestLinuxVideo.mp4");

        InitializedUploadFileInfoDTO initializedUploadFileInfoDTO = new InitializedUploadFileInfoDTO();
        initializedUploadFileInfoDTO.setFileMD5(DigestUtils.md5DigestAsHex(new FileInputStream(file)));
        initializedUploadFileInfoDTO.setFilename(file.getName());
        initializedUploadFileInfoDTO.setTotalBlockLength(1);
        initializedUploadFileInfoDTO.setTotalByteSize(file.length());

        String s = new Gson().toJson(initializedUploadFileInfoDTO);

        log.info("文件初始化信息,请求内容:{}",s);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.putAll(headers);
        httpHeaders.add("Cookie",cookies.get(0));  //这里设置base64解码之前的字符串,因为Security框架会进行解码判断是否登录的

        HttpEntity<String> stringHttpEntity = new HttpEntity<>(s,httpHeaders);

        BaseResponseDataVo baseResponseDataVo = testRestTemplate.postForObject("/upload/init", stringHttpEntity, BaseResponseDataVo.class);
        System.out.println(baseResponseDataVo);


    }

}

 

 

这里看下SpringBoot测试部分的文档:

SpringBoot测试服务器部分说明(完整运行服务器)

TestRestTemplate类文档的部分说明

 

综合以上,就应该已经很清楚了,上面的代码部分就不一一说明了,欢迎下方留言

posted @ 2020-10-21 22:19  星小梦  阅读(884)  评论(0编辑  收藏  举报