博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring mvc+junit
阅读量:6440 次
发布时间:2019-06-23

本文共 5833 字,大约阅读时间需要 19 分钟。

  hot3.png

spring mvc的简单单元测试,说白了就是测试spring mvc的controller.

先参考两篇帖子:

1.http://spring.io/blog/2011/06/21/spring-3-1-m2-testing-with-configuration-classes-and-profiles

2.http://spring.io/blog/2012/11/07/spring-framework-3-2-rc1-new-testing-features

实践:

UserController.java

package com.test.web;import java.io.File;import java.io.IOException;import java.util.List;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.util.FileCopyUtils;import org.springframework.web.bind.annotation.RequestBody;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.ResponseBody;import org.springframework.web.multipart.MultipartFile;import com.test.domain.User;import com.test.service.UserService;@Controller@RequestMapping("/user")public class UserController{	private static final String FILES_DIR="e:/";	@Resource	private UserService userService;	@RequestMapping("/save")	public String save(User user) {		userService.save(user);		return "result";	}	@RequestMapping("/getUser")	public @ResponseBody User getUser(HttpServletRequest request,@RequestBody User user) {		System.out.println("AAAAAAA::"+user);		request.setAttribute("data1",user);		return user;	}	@RequestMapping("/getUsers")	public @ResponseBody List
getUsers(HttpServletRequest request,@RequestBody List
users) { System.out.println(users.getClass().getName()); for (User user : users) { System.out.println("BBBBBBBB::"+user); } request.setAttribute("data2", users); return users; } @RequestMapping(value = "/upload", method = RequestMethod.POST) public String add(HttpServletRequest request,@RequestParam("file") MultipartFile file) { //System.out.println("real path::"+request.getServletContext().getRealPath("/")); String filename=file.getOriginalFilename(); File tmpFile=new File(FILES_DIR+filename); if(filename!=null&&!file.isEmpty()){ try { FileCopyUtils.copy(file.getBytes(), tmpFile); System.out.println("上传成功"); } catch (IOException e) { e.printStackTrace(); } } return "result"; } }
2.UserControllerTest.java

package com.test.web;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;import java.io.IOException;import java.util.ArrayList;import java.util.List;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.mock.web.MockMultipartFile;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import org.springframework.test.context.web.WebAppConfiguration;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.setup.MockMvcBuilders;import org.springframework.web.context.WebApplicationContext;import com.test.config.AppConfig;import com.test.domain.User;import com.test.util.JsonUtil;@RunWith(SpringJUnit4ClassRunner.class)@WebAppConfiguration@ContextConfiguration(classes={ AppConfig.class})public class UserControllerTest {	@Autowired	private WebApplicationContext webApplicationContext;	private MockMvc mockMvc;	@Before	public void init(){		mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();	}	@Test	public void printBeans(){		String[] beans=webApplicationContext.getBeanDefinitionNames();		for (String bean : beans) {			System.out.println(bean);		}	}	/*测试以普通请求参数发送的请求*/	@Test	public void testSave() throws Exception {		mockMvc.perform(post("/user/save").param("id", "123").param("username", "you")).andExpect(status().isOk()).andExpect(view().name("result"));	}	/*测试将数据以JSON格式写入请求体发送的请求*/	@Test	public void testGet() throws Exception {		mockMvc.perform(post("/user/getUser").contentType(JsonUtil.APPLICATION_JSON_UTF8).content(JsonUtil.convertObjectToJsonBytes(new User(22,"werwr")))).andExpect(status().isOk());	}	/*测试将数据以JSON格式写入请求体发送的请求*/	@Test	public void testGetAll() throws IOException, Exception {		List
list=new ArrayList
(); list.add(new User(23,"你爱我")); list.add(new User(25,"我不爱你")); mockMvc.perform(post("/user/getUsers").contentType(JsonUtil.APPLICATION_JSON_UTF8).content(JsonUtil.convertObjectToJsonBytes(list))).andExpect(status().isOk()); } /*测试文件上传发送的请求*/ @Test public void testUpload() throws Exception{ MockMultipartFile file = new MockMultipartFile("file", "orig.txt", null, "bar".getBytes()); mockMvc.perform(fileUpload("/user/upload").file(file)).andExpect(status().isOk()); }}
以上就贴出了spring mvc的单元测试最核心内容和举例的最核心代码.

完整源代码:

顺便贴一下spring junit(非controller简单bean)

package com.test.service;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.test.domain.User;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfigurationpublic class UserServiceTest {	@Configuration	@ComponentScan(basePackages={"com.test.service"})	static class ContextConfiguration {}	@Resource	private UserService userService;		@Test	public void testSave(){		userService.save(new User(123,"xxx"));	}}

版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://my.oschina.net/mayude/blog/503638

你可能感兴趣的文章
位运算符总结
查看>>
分布式工作流任务调度系统Easy Scheduler正式开源
查看>>
如何进入一个新领域
查看>>
Android屏幕适配讲解与实战
查看>>
阿里云容器服务ACK发布Windows Container支持,让Windows应用快速上云 ...
查看>>
空间碎片化处理
查看>>
【第9期】自动驾驶出租车到底“破坏力”几何?麦肯锡这份报告告诉你 ...
查看>>
提高网络营销的转化只需掌握这四步
查看>>
Docker 和 Kubernetes 从听过到略懂:给程序员的旋风教程 ...
查看>>
直播系统源码让您看清现代播放器的架构
查看>>
解决IntelliJ IDEA无法读取配置*.properties文件的问题 ...
查看>>
杨老师课堂_Java核心技术下之控制台模拟文件管理器案例
查看>>
书籍:Data Cleaning数据清洗-基于shell和python - 2018.pdf
查看>>
2019,互联网带给制造业的危与机
查看>>
Django的Project和App的区别
查看>>
springboot打包不同环境配置与shell脚本部署
查看>>
第二十三章:触发器和行为(六)
查看>>
解密阿里视频云女程序员米悠代码诗!
查看>>
京东要做IPv6急行军
查看>>
HanLPTokenizer HanLP分词器
查看>>