1. 今天介绍一下springMVC的单元测试,可以参考spring官方文档进行
  2. 前提准备,springmvcdemo工程,这里就不做叙述了
  3. pom.xml
  4. [html] view plain copy CODE上查看代码片派生到我的代码片
  5. <dependency>
  6. <groupId>org.springframework</groupId>
  7. <artifactId>spring-core</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.springframework</groupId>
  11. <artifactId>spring-beans</artifactId>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.springframework</groupId>
  15. <artifactId>spring-context</artifactId>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.springframework</groupId>
  19. <artifactId>spring-context-support</artifactId>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework</groupId>
  23. <artifactId>spring-web</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework</groupId>
  27. <artifactId>spring-webmvc</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework</groupId>
  31. <artifactId>spring-orm</artifactId>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework</groupId>
  35. <artifactId>spring-tx</artifactId>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.springframework</groupId>
  39. <artifactId>spring-test</artifactId>
  40. </dependency>
  41. <dependency>
  42. <groupId>junit</groupId>
  43. <artifactId>junit</artifactId>
  44. </dependency>
  45.  
  46. controller
  47. [java] view plain copy CODE上查看代码片派生到我的代码片
  48. package controller;
  49.  
  50. import javax.servlet.http.HttpSession;
  51.  
  52. import org.springframework.beans.factory.annotation.Autowired;
  53. import org.springframework.web.bind.annotation.PathVariable;
  54. import org.springframework.web.bind.annotation.RequestMapping;
  55. import org.springframework.web.bind.annotation.RequestMethod;
  56. import org.springframework.web.bind.annotation.RequestParam;
  57. import org.springframework.web.bind.annotation.RestController;
  58.  
  59. import service.UserService;
  60. import domain.User;
  61.  
  62. /**
  63. * UserController.
  64. * @author Leon Lee
  65. */
  66. @RestController
  67. @RequestMapping(value = "user")
  68. public class UserController {
  69.  
  70. /**
  71. * UserService interface.
  72. */
  73. @Autowired
  74. private UserService userService;
  75.  
  76. /**
  77. * Get user MSG.
  78. * @param userId
  79. * @return user Msg
  80. */
  81. @RequestMapping(value = "userMsg/{userId}", method = RequestMethod.GET)
  82. public User getUserMsg(@PathVariable(value = "userId") String userId) {
  83. return userService.getUserMsg(userId);
  84. }
  85.  
  86. /**
  87. * Update user MSG.
  88. * @param userId
  89. * @param userName
  90. * @return updated user MSG
  91. */
  92. @RequestMapping(value = "userMsg/{userId}", method = RequestMethod.PUT)
  93. public User putUserMsg(@PathVariable(value = "userId") String userId, @RequestParam String userName,HttpSession session){
  94. if(null == (String)session.getAttribute("loginUser"))
  95. return new User();
  96. System.out.println((String)session.getAttribute("loginUser"));
  97. return userService.putUserMsg(userId, userName);
  98. }
  99.  
  100. /**
  101. * Delete user.
  102. * @param userId
  103. * @return deleted user MSG
  104. */
  105. @RequestMapping(value = "userMsg/{userId}", method = RequestMethod.DELETE)
  106. public User delUserMsg(@PathVariable(value = "userId") String userId){
  107. return userService.delUserMsg(userId);
  108. }
  109.  
  110. /**
  111. * Add user.
  112. * @param userName
  113. * @return added user MSG
  114. */
  115. @RequestMapping(value = "userMsg", method = RequestMethod.POST)
  116. public User postUserMsg(@RequestParam String userName){
  117. return userService.postUserMsg(userName);
  118. }
  119.  
  120. /**
  121. * login User. Note that do not send password as url.
  122. * @param userId
  123. * @param password
  124. * @return
  125. */
  126. @RequestMapping(value = "userMsg/{userId}/{password}", method = RequestMethod.GET)
  127. public boolean loginUser(@PathVariable String userId, @PathVariable String password, HttpSession session){
  128. if("loginUser".equals(userId)&&"loginUser".equals(password)){
  129. session.setAttribute("loginUser", userId);
  130. return true;
  131. }
  132. return false;
  133. }
  134. }
  135.  
  136. 单元测试类
  137. 这里的静态导入比较重要,有时候没办法自动导入的
  138. 就是下面的 import static xxx.*
  139.  
  140. 另一点,
  141. [java] view plain copy CODE上查看代码片派生到我的代码片
  142. @ContextConfiguration(locations = {"classpath:applicationContext.xml","classpath:applicationContext.mvc.xml"})
  143. 代表的是加载的配置文件,可以根据需要进行添加
  144.  
  145. [java] view plain copy CODE上查看代码片派生到我的代码片
  146. package controller.test;
  147.  
  148. import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
  149. import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
  150. import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
  151. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
  152.  
  153. import javax.servlet.http.HttpSession;
  154.  
  155. import org.junit.Before;
  156. import org.junit.Test;
  157. import org.junit.runner.RunWith;
  158. import org.springframework.beans.factory.annotation.Autowired;
  159. import org.springframework.http.MediaType;
  160. import org.springframework.mock.web.MockHttpSession;
  161. import org.springframework.test.annotation.Rollback;
  162. import org.springframework.test.context.ContextConfiguration;
  163. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  164. import org.springframework.test.context.transaction.TransactionConfiguration;
  165. import org.springframework.test.context.web.WebAppConfiguration;
  166. import org.springframework.test.web.servlet.MockMvc;
  167. import org.springframework.test.web.servlet.MvcResult;
  168. import org.springframework.transaction.annotation.Transactional;
  169. import org.springframework.web.context.WebApplicationContext;
  170.  
  171. /**
  172. * spring mvc Test.
  173. * @author Leon Lee
  174. * @since spring-4.1.7
  175. */
  176. // spring 4.3 change to SpringRunner.class
  177. @RunWith(SpringJUnit4ClassRunner.class)
  178. @WebAppConfiguration
  179. @ContextConfiguration(locations = {"classpath:applicationContext.xml","classpath:applicationContext.mvc.xml"})
  180. // do rollback
  181. @TransactionConfiguration(defaultRollback = true)
  182. @Transactional
  183. public class TestTemplate {
  184. @Autowired
  185. private WebApplicationContext wac;
  186.  
  187. private MockMvc mockMvc;
  188. private MockHttpSession session;
  189.  
  190. @Before
  191. public void setup() {
  192. // init applicationContext
  193. this.mockMvc = webAppContextSetup(this.wac).build();
  194. this.session = new MockHttpSession();
  195. }
  196.  
  197. @Test
  198. public void getUserMsg() throws Exception {
  199. // get using get
  200. this.mockMvc
  201. .perform((get("/user/userMsg/003"))
  202. .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
  203. .andExpect(status().isOk())
  204. .andExpect(content().contentType("application/json;charset=UTF-8"))
  205. .andDo(print()); // print
  206. }
  207.  
  208. @Test
  209. // don't rollback
  210. @Rollback(false)
  211. public void putUserMsg() throws Exception {
  212. // update using put
  213. this.mockMvc
  214. .perform((put("/user/userMsg/003"))
  215. .contentType(MediaType.APPLICATION_FORM_URLENCODED)
  216. .param("userName","新名字03号")
  217. .session((MockHttpSession)getLoginSession())
  218. .accept(MediaType.parseMediaType("application/json;charset=UTF-8"))
  219. )
  220. .andExpect(status().isOk())
  221. .andExpect(content().contentType("application/json;charset=UTF-8"))
  222. .andDo(print()); // print
  223. }
  224.  
  225. @Test
  226. public void delUser() throws Exception {
  227. // delete using delete
  228. this.mockMvc
  229. .perform((delete("/user/userMsg/004"))
  230. .accept(MediaType.parseMediaType("application/json;charset=UTF-8"))
  231. )
  232. .andExpect(status().isOk())
  233. .andExpect(content().contentType("application/json;charset=UTF-8"))
  234. .andDo(print()); //print
  235. }
  236.  
  237. @Test
  238. // don't rollback
  239. @Rollback(false)
  240. public void postUser() throws Exception{
  241. // add using post
  242. this.mockMvc
  243. .perform((post("/user/userMsg"))
  244. .param("userName", "最新的用户")
  245. .accept(MediaType.parseMediaType("application/json;charset=UTF-8"))
  246. )
  247. .andExpect(status().isOk())
  248. .andExpect(content().contentType("application/json;charset=UTF-8"))
  249. .andDo(print()); //print
  250. }
  251.  
  252. /**
  253. * 获取登入信息session
  254. * @return
  255. * @throws Exception
  256. */
  257. private HttpSession getLoginSession() throws Exception{
  258. // mock request get login session
  259. // url = /xxx/xxx/{username}/{password}
  260. MvcResult result = this.mockMvc
  261. .perform((get("/user/userMsg/loginUser/loginUser")))
  262. .andExpect(status().isOk())
  263. .andReturn();
  264. return result.getRequest().getSession();
  265. }
  266. }

SpringMVC单元测试之MockMVC,模拟登入用户的更多相关文章

  1. vuex存取token,http简单封装、模拟登入权限校验操作、路由懒加载的几种方式、vue单页设置title

    1.config index.js下面的跨域代理设置: proxyTable: { '/api': { target: 'http://xxxx', //要访问的后端接口 changeOrigin: ...

  2. spring boot单元测试之MockMvc

    spring单元测试之MockMvc,这个只是模拟,并不是真正的servlet,所以session.servletContext是没法用的. @RunWith(SpringRunner.class) ...

  3. Python爬虫-尝试使用人工和OCR处理验证码模拟登入

    刚开始在网上看别人一直在说知乎登入首页有有倒立的汉字验证码,我打开自己的知乎登入页面,发现只有账号和密码,他们说的倒立的验证码去哪了,后面仔细一想我之前登入过知乎,应该在本地存在cookies,然后我 ...

  4. 【Android Training - UserInfo】记住登入用户的信息[Lesson 1 - 使用AccountManager来记住用户]

    Remembering Your User[记住你的用户] 每一个人都非常喜欢自己的名字能被人记住.当中最简单,最有效的使得你的app让人喜欢的方法是记住你的用户是谁,特别是当用户升级到一台新的设备或 ...

  5. springmvc shiro整合cas单点登入

    shiro cas分为登入跟登出 maven依赖: <dependency> <groupId>org.apache.shiro</groupId> <art ...

  6. 8-python模拟登入(无验证码)

    方式: 1.手动登入,获取cookie 2.使用cookielib库 和 HTTPCookieProcessor处理器 #_*_ coding: utf-8 _*_ ''' Created on 20 ...

  7. Junit单元测试之MockMvc

    在测试restful风格的接口时,springmvc为我们提供了MockMVC架构,使用起来也很方便. 下面写个笔记,便于以后使用时参考备用. 一 场景 1 . 提供一个restful风格的接口 im ...

  8. 模拟登入教务处(header)

    import HTMLParser import urlparse import urllib import urllib2 import cookielib import string import ...

  9. [Django]登陆界面以及用户登入登出权限

    前言:简单的登陆界面展现,以及用户登陆登出,最后用户权限的问题 正文: 首先需要在settings.py设置ROOT_URLCONF,默认值为: ROOT_URLCONF  = 'www.urls'# ...

随机推荐

  1. XAF视频教程来啦,已出7课

        XAF交流学习群内的兄弟录制了视频,他没有博客,委拖我发至博客园,希望能让更多的开发人员受益.快速开发企业级应用的好工具!   XAF入门01快速浏览   XAF入门02特点. XAF入门03 ...

  2. Redis和Memcached整体

    Redis和Memcached整体对比 Redis的作者Salvatore Sanfilippo曾经对这两种基于内存的数据存储系统进行过比较,总体来看还是比较客观的,现总结如下: 1)性能对比:由于R ...

  3. IDE有毒

    程序员按项目性质大致有三种:写Demo的.写Proto的.写成品的:按项目开发周期大致有:写开头的.写中间的.写结尾的. Demo是样品,主要是表面上初步实现,临时忽悠客户用的,不一定要求继续演化: ...

  4. mybatis报错invalid types () or values ()解决方法

      原因: Pojo类User没提供无参数构造方法, 加上该构造方法后,问题解决 ### Cause: org.apache.ibatis.reflection.ReflectionException ...

  5. Java 代码完成删除文件、文件夹操作

    import java.io.File;/** * 删除文件和目录 * */public class DeleteFileUtil {    /**     * 删除文件,可以是文件或文件夹     ...

  6. Sublime Text使用配置介绍

    这篇文章很多内容都是来源自网络,发布这里当作自己留个底,以后不用到处去找 对于文本编辑器,我用过notepad2.notepad++.Editplus.UltraEdit.Vim.TextPad,都没 ...

  7. 悟透JavaScript(理解JS面向对象的好文章)

    引子 编程世界里只存在两种基本元素,一个是数据,一个是代码.编程世界就是在数据和代码千丝万缕的纠缠中呈现出无限的生机和活力. 数据天生就是文静的,总想保持自己固有的本色:而代码却天生活泼,总想改变这个 ...

  8. 编写可维护的CSS

    在参与规模庞大.历时漫长且参与人数众多的项目时,所有开发者遵守如下规则极为重要: 保持 CSS 便于维护 保持代码清晰易懂 保持代码的可拓展性 为了实现这一目标,我们要采用诸多方法. 本文档第一部分将 ...

  9. Json.NET读取和写入Json文件

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  10. AngularJS中的指令全面解析(转载)

    说到AngularJS,我们首先想到的大概也就是双向数据绑定和指令系统了,这两者也是AngularJS中最为吸引人的地方.双向数据绑定呢,感觉没什么好说的,那么今天我们就来简单的讨论下AngularJ ...