spring boot单元测试之六:用mockmvc模拟cookie(spring boot 2.4.3)

一,演示项目的相关信息

1,地址:

https://github.com/liuhongdi/cookietest

2,功能说明:演示mockmvc访问controller时提交cookie

3,项目结构:如图:

说明:刘宏缔的架构森林是一个专注架构的博客,

网站:https://blog.imgtouch.com
本文: https://blog.imgtouch.com/index.php/2023/05/27/spring-boot-dan-yuan-ce-shi-zhi-liu-yong-mockmvc-mo-ni/

         对应的源码可以访问这里获取: https://github.com/liuhongdi/

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,java代码说明

1,controller/UserController.java

复制代码
@RestController
@RequestMapping("/user")
public class UserController {

    //读取session
    @GetMapping("/get")
    public String getcookie(@CookieValue(value = "username", defaultValue = "") String username) {
        System.out.println("get cookie:"+username);
        return "" + username;
    }

    //设置session
    @GetMapping("/set")
    public String setcookie(@RequestParam("userName")String userName, HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = new Cookie("username", userName);
        //过期时间,单位是:秒(s)
        cookie.setMaxAge(30 * 24 * 60 * 60);
        //cookie.setPath(request.getContextPath());
        cookie.setPath("/");
        response.addCookie(cookie);
        System.out.println("set cookie:"+userName);

        return userName;
    }
}
复制代码

 

2,controller/UserControllerTest.java

复制代码
@AutoConfigureMockMvc
@SpringBootTest
class UserControllerTest {

    @Autowired
    private UserController userController;

    @Autowired
    private MockMvc mockMvc;

    @Test
    @DisplayName("测试读取cookie值")
    void getCookie() throws Exception{
        Cookie cookieu = new Cookie("username", "mr liu");
        //过期时间,单位是:秒(s)
        cookieu.setMaxAge(30 * 24 * 60 * 60);
        cookieu.setPath("/");
        //query
        MvcResult mvcResult = mockMvc.perform(get("/user/get")
                .cookie(cookieu)
                .contentType(MediaType.APPLICATION_FORM_URLENCODED))
                .andReturn();
        String content = mvcResult.getResponse().getContentAsString();
        assertThat(content, equalTo("mr liu"));
    }

    @Test
    @DisplayName("测试读取cookie值失败")
    void getCookieFail() throws Exception{
        //query
        MvcResult mvcResult = mockMvc.perform(get("/user/get")
                //.cookie(cookieu)
                .contentType(MediaType.APPLICATION_FORM_URLENCODED))
                .andReturn();
        String content = mvcResult.getResponse().getContentAsString();
        assertThat(content, equalTo(""));
    }
    
    @Test
    @DisplayName("测试写cookie值")
    void setCookie() throws Exception{
        String cookieValue="laoliu123aaa";
        //query
        MvcResult mvcResult = mockMvc.perform(get("/user/set?userName="+cookieValue)
                .contentType(MediaType.APPLICATION_FORM_URLENCODED))
                .andReturn();
        String content = mvcResult.getResponse().getContentAsString();
        assertThat(content, equalTo(cookieValue));

    }
}
复制代码

 

三,效果测试

1,查接访问url测试

set cookie:

http://127.0.0.1:8080/user/set?userName=laoliu123

get cookie:

http://127.0.0.1:8080/user/get

返回:

2,执行单元测试:

四,查看spring boot的版本:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.3)

 

posted @   刘宏缔的架构森林  阅读(1293)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
历史上的今天:
2020-03-26 centos8平台使用slabtop监控slab内存的状态
2020-03-26 centos8上使用lsblk查看块设备
2020-03-26 centos8环境判断当前操作系统是否虚拟机或容器
2020-03-26 centos8平台使用lscpu查看cpu信息
2020-03-26 centos8平台使用pidstat监控cpu/内存/io
点击右上角即可分享
微信分享提示