一,演示項目的相關信息
1,地址:
https://github.com/liuhongdi/sessiontest
2,功能說明:
演示了用mockmvc模擬有session時的操作
3,項目結構:如圖:

說明:劉宏締的架構森林是一個專注架構的博客,地址:https://www.cnblogs.com/architectforest
對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/
說明:作者:劉宏締 郵箱: 371125307@qq.com
二,java代碼說明
1,controller/UserController.java
@RestController @RequestMapping("/user") public class UserController { //讀取session @GetMapping("/get") public String getsess(HttpServletRequest request) { HttpSession session=request.getSession(); String username = (String)session.getAttribute("username"); System.out.println("session username:"+username); if (username == null) { return ""; } else { return username; } } //設置session @GetMapping("/set") public String setSess(@RequestParam("userName")String userName, HttpServletRequest request) { HttpSession session=request.getSession(); session.setAttribute("username", userName); //判斷寫入是否成功? String nameret = (String)session.getAttribute("username"); System.out.println("set session username and read:"+nameret); return nameret; } }
2,controller/UserControllerTest.java
@AutoConfigureMockMvc @SpringBootTest class UserControllerTest { @Autowired private UserController userController; @Autowired private MockMvc mockMvc; private static MockHttpSession sessionPub; /** * 測試方法開始之前執行 設置模擬Mvc */ @BeforeAll public static void setupMockMvc() { sessionPub = new MockHttpSession(); sessionPub.setAttribute("username", "liuhongdi"); } @Test @DisplayName("測試get用戶名,有session") void getTest() throws Exception { //MockHttpSession session = new MockHttpSession(); //session.setAttribute("username", "liuhongdi"); MvcResult mvcResult = mockMvc.perform(get("/user/get") .session(sessionPub) .contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andReturn(); String content = mvcResult.getResponse().getContentAsString(); assertThat(content, equalTo("liuhongdi")); } @Test @DisplayName("測試get用戶名,無session") void getTestFail() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/user/get") .contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andReturn(); String content = mvcResult.getResponse().getContentAsString(); assertThat(content, equalTo("")); } @Test @DisplayName("測試set session") void setTest() throws Exception { String name="mr liu"; MvcResult mvcResult = mockMvc.perform(get("/user/set?userName="+name) .session(sessionPub) .contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andReturn(); String content = mvcResult.getResponse().getContentAsString(); assertThat(content, equalTo("mr liu")); } }
三,測試效果
1,訪問url查看效果:
設置session
http://127.0.0.1:8080/user/set?userName=laoliuabc
如圖:

讀取session:
訪問:
http://127.0.0.1:8080/user/get
如圖:

2,運行單元測試:

四,查看spring boot的版本:
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.4.3)
