SpringMVC单元测试之MockMVC,模拟登入用户
- 今天介绍一下springMVC的单元测试,可以参考spring官方文档进行
- 前提准备,springmvc的demo工程,这里就不做叙述了
- pom.xml
- [html] view plain copy 在CODE上查看代码片派生到我的代码片
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-beans</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-orm</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-tx</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- </dependency>
- controller层
- [java] view plain copy 在CODE上查看代码片派生到我的代码片
- package controller;
- import javax.servlet.http.HttpSession;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.RestController;
- import service.UserService;
- import domain.User;
- /**
- * UserController.
- * @author Leon Lee
- */
- @RestController
- @RequestMapping(value = "user")
- public class UserController {
- /**
- * UserService interface.
- */
- @Autowired
- private UserService userService;
- /**
- * Get user MSG.
- * @param userId
- * @return user Msg
- */
- @RequestMapping(value = "userMsg/{userId}", method = RequestMethod.GET)
- public User getUserMsg(@PathVariable(value = "userId") String userId) {
- return userService.getUserMsg(userId);
- }
- /**
- * Update user MSG.
- * @param userId
- * @param userName
- * @return updated user MSG
- */
- @RequestMapping(value = "userMsg/{userId}", method = RequestMethod.PUT)
- public User putUserMsg(@PathVariable(value = "userId") String userId, @RequestParam String userName,HttpSession session){
- if(null == (String)session.getAttribute("loginUser"))
- return new User();
- System.out.println((String)session.getAttribute("loginUser"));
- return userService.putUserMsg(userId, userName);
- }
- /**
- * Delete user.
- * @param userId
- * @return deleted user MSG
- */
- @RequestMapping(value = "userMsg/{userId}", method = RequestMethod.DELETE)
- public User delUserMsg(@PathVariable(value = "userId") String userId){
- return userService.delUserMsg(userId);
- }
- /**
- * Add user.
- * @param userName
- * @return added user MSG
- */
- @RequestMapping(value = "userMsg", method = RequestMethod.POST)
- public User postUserMsg(@RequestParam String userName){
- return userService.postUserMsg(userName);
- }
- /**
- * login User. Note that do not send password as url.
- * @param userId
- * @param password
- * @return
- */
- @RequestMapping(value = "userMsg/{userId}/{password}", method = RequestMethod.GET)
- public boolean loginUser(@PathVariable String userId, @PathVariable String password, HttpSession session){
- if("loginUser".equals(userId)&&"loginUser".equals(password)){
- session.setAttribute("loginUser", userId);
- return true;
- }
- return false;
- }
- }
- 单元测试类
- 这里的静态导入比较重要,有时候没办法自动导入的
- 就是下面的 import static xxx.*
- 另一点,
- [java] view plain copy 在CODE上查看代码片派生到我的代码片
- @ContextConfiguration(locations = {"classpath:applicationContext.xml","classpath:applicationContext.mvc.xml"})
- 代表的是加载的配置文件,可以根据需要进行添加
- [java] view plain copy 在CODE上查看代码片派生到我的代码片
- package controller.test;
- import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
- import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
- import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
- import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
- import javax.servlet.http.HttpSession;
- import org.junit.Before;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.http.MediaType;
- import org.springframework.mock.web.MockHttpSession;
- import org.springframework.test.annotation.Rollback;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
- import org.springframework.test.context.transaction.TransactionConfiguration;
- import org.springframework.test.context.web.WebAppConfiguration;
- import org.springframework.test.web.servlet.MockMvc;
- import org.springframework.test.web.servlet.MvcResult;
- import org.springframework.transaction.annotation.Transactional;
- import org.springframework.web.context.WebApplicationContext;
- /**
- * spring mvc Test.
- * @author Leon Lee
- * @since spring-4.1.7
- */
- // spring 4.3 change to SpringRunner.class
- @RunWith(SpringJUnit4ClassRunner.class)
- @WebAppConfiguration
- @ContextConfiguration(locations = {"classpath:applicationContext.xml","classpath:applicationContext.mvc.xml"})
- // do rollback
- @TransactionConfiguration(defaultRollback = true)
- @Transactional
- public class TestTemplate {
- @Autowired
- private WebApplicationContext wac;
- private MockMvc mockMvc;
- private MockHttpSession session;
- @Before
- public void setup() {
- // init applicationContext
- this.mockMvc = webAppContextSetup(this.wac).build();
- this.session = new MockHttpSession();
- }
- @Test
- public void getUserMsg() throws Exception {
- // get using get
- this.mockMvc
- .perform((get("/user/userMsg/003"))
- .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
- .andExpect(status().isOk())
- .andExpect(content().contentType("application/json;charset=UTF-8"))
- .andDo(print()); // print
- }
- @Test
- // don't rollback
- @Rollback(false)
- public void putUserMsg() throws Exception {
- // update using put
- this.mockMvc
- .perform((put("/user/userMsg/003"))
- .contentType(MediaType.APPLICATION_FORM_URLENCODED)
- .param("userName","新名字03号")
- .session((MockHttpSession)getLoginSession())
- .accept(MediaType.parseMediaType("application/json;charset=UTF-8"))
- )
- .andExpect(status().isOk())
- .andExpect(content().contentType("application/json;charset=UTF-8"))
- .andDo(print()); // print
- }
- @Test
- public void delUser() throws Exception {
- // delete using delete
- this.mockMvc
- .perform((delete("/user/userMsg/004"))
- .accept(MediaType.parseMediaType("application/json;charset=UTF-8"))
- )
- .andExpect(status().isOk())
- .andExpect(content().contentType("application/json;charset=UTF-8"))
- .andDo(print()); //print
- }
- @Test
- // don't rollback
- @Rollback(false)
- public void postUser() throws Exception{
- // add using post
- this.mockMvc
- .perform((post("/user/userMsg"))
- .param("userName", "最新的用户")
- .accept(MediaType.parseMediaType("application/json;charset=UTF-8"))
- )
- .andExpect(status().isOk())
- .andExpect(content().contentType("application/json;charset=UTF-8"))
- .andDo(print()); //print
- }
- /**
- * 获取登入信息session
- * @return
- * @throws Exception
- */
- private HttpSession getLoginSession() throws Exception{
- // mock request get login session
- // url = /xxx/xxx/{username}/{password}
- MvcResult result = this.mockMvc
- .perform((get("/user/userMsg/loginUser/loginUser")))
- .andExpect(status().isOk())
- .andReturn();
- return result.getRequest().getSession();
- }
- }
SpringMVC单元测试之MockMVC,模拟登入用户的更多相关文章
- vuex存取token,http简单封装、模拟登入权限校验操作、路由懒加载的几种方式、vue单页设置title
1.config index.js下面的跨域代理设置: proxyTable: { '/api': { target: 'http://xxxx', //要访问的后端接口 changeOrigin: ...
- spring boot单元测试之MockMvc
spring单元测试之MockMvc,这个只是模拟,并不是真正的servlet,所以session.servletContext是没法用的. @RunWith(SpringRunner.class) ...
- Python爬虫-尝试使用人工和OCR处理验证码模拟登入
刚开始在网上看别人一直在说知乎登入首页有有倒立的汉字验证码,我打开自己的知乎登入页面,发现只有账号和密码,他们说的倒立的验证码去哪了,后面仔细一想我之前登入过知乎,应该在本地存在cookies,然后我 ...
- 【Android Training - UserInfo】记住登入用户的信息[Lesson 1 - 使用AccountManager来记住用户]
Remembering Your User[记住你的用户] 每一个人都非常喜欢自己的名字能被人记住.当中最简单,最有效的使得你的app让人喜欢的方法是记住你的用户是谁,特别是当用户升级到一台新的设备或 ...
- springmvc shiro整合cas单点登入
shiro cas分为登入跟登出 maven依赖: <dependency> <groupId>org.apache.shiro</groupId> <art ...
- 8-python模拟登入(无验证码)
方式: 1.手动登入,获取cookie 2.使用cookielib库 和 HTTPCookieProcessor处理器 #_*_ coding: utf-8 _*_ ''' Created on 20 ...
- Junit单元测试之MockMvc
在测试restful风格的接口时,springmvc为我们提供了MockMVC架构,使用起来也很方便. 下面写个笔记,便于以后使用时参考备用. 一 场景 1 . 提供一个restful风格的接口 im ...
- 模拟登入教务处(header)
import HTMLParser import urlparse import urllib import urllib2 import cookielib import string import ...
- [Django]登陆界面以及用户登入登出权限
前言:简单的登陆界面展现,以及用户登陆登出,最后用户权限的问题 正文: 首先需要在settings.py设置ROOT_URLCONF,默认值为: ROOT_URLCONF = 'www.urls'# ...
随机推荐
- XAF视频教程来啦,已出7课
XAF交流学习群内的兄弟录制了视频,他没有博客,委拖我发至博客园,希望能让更多的开发人员受益.快速开发企业级应用的好工具! XAF入门01快速浏览 XAF入门02特点. XAF入门03 ...
- Redis和Memcached整体
Redis和Memcached整体对比 Redis的作者Salvatore Sanfilippo曾经对这两种基于内存的数据存储系统进行过比较,总体来看还是比较客观的,现总结如下: 1)性能对比:由于R ...
- IDE有毒
程序员按项目性质大致有三种:写Demo的.写Proto的.写成品的:按项目开发周期大致有:写开头的.写中间的.写结尾的. Demo是样品,主要是表面上初步实现,临时忽悠客户用的,不一定要求继续演化: ...
- mybatis报错invalid types () or values ()解决方法
原因: Pojo类User没提供无参数构造方法, 加上该构造方法后,问题解决 ### Cause: org.apache.ibatis.reflection.ReflectionException ...
- Java 代码完成删除文件、文件夹操作
import java.io.File;/** * 删除文件和目录 * */public class DeleteFileUtil { /** * 删除文件,可以是文件或文件夹 ...
- Sublime Text使用配置介绍
这篇文章很多内容都是来源自网络,发布这里当作自己留个底,以后不用到处去找 对于文本编辑器,我用过notepad2.notepad++.Editplus.UltraEdit.Vim.TextPad,都没 ...
- 悟透JavaScript(理解JS面向对象的好文章)
引子 编程世界里只存在两种基本元素,一个是数据,一个是代码.编程世界就是在数据和代码千丝万缕的纠缠中呈现出无限的生机和活力. 数据天生就是文静的,总想保持自己固有的本色:而代码却天生活泼,总想改变这个 ...
- 编写可维护的CSS
在参与规模庞大.历时漫长且参与人数众多的项目时,所有开发者遵守如下规则极为重要: 保持 CSS 便于维护 保持代码清晰易懂 保持代码的可拓展性 为了实现这一目标,我们要采用诸多方法. 本文档第一部分将 ...
- Json.NET读取和写入Json文件
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...
- AngularJS中的指令全面解析(转载)
说到AngularJS,我们首先想到的大概也就是双向数据绑定和指令系统了,这两者也是AngularJS中最为吸引人的地方.双向数据绑定呢,感觉没什么好说的,那么今天我们就来简单的讨论下AngularJ ...