SpringMVC controller测试较简单,从功能角度划分,可分为两种。一种是调用请求路径测试,另一种是直接调用Controller方法测试。

调用请求路径测试

通过请求路径调用,请求需要经过拦截器,再到对应的Controller方法处理

被测试代码示例

import com.agoura.agoura.entity.Members;
import com.agoura.agoura.service.MembersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; @Controller
@RequestMapping("/api")
public class MembersController { @Autowired
private MembersService membersService; @RequestMapping(value = "/user", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public String getUser(HttpServletRequest request, @RequestBody String str,
@RequestParam(value = "userId") String userId) {
Members result = membersService.getMemberById(Integer.valueOf(userId));
return result.toString();
}
}

测试代码示例

import com.agoura.agoura.entity.Members;
import com.agoura.agoura.service.MembersService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) //调用Spring单元测试类
@WebAppConfiguration //调用Java Web组件,如自动注入ServletContext Bean等
@ContextConfiguration(locations = {"classpath*:spring-*.xml"}) //加载Spring配置文件
public class MembersControllerTest2 { @Autowired
protected WebApplicationContext wac; @Mock
private MembersService service; @InjectMocks
private MembersController controller; //需要测试的Controller private MockMvc mockMvc; //SpringMVC提供的Controller测试类 private String url; @Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(wac).build();
} @Test
public void testGetUser() throws Exception {
url = "the URL to Controller"; Members m = new Members(3, "wangwu", 1, 5, "12131232342");
when(service.getMemberById(Mockito.anyInt())).thenReturn(m); MvcResult result = mockMvc
.perform(MockMvcRequestBuilders.post(url)
.accept(MediaType.APPLICATION_JSON)
.param("userId", "3"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(model().attributeExists("name"))
.andReturn();
assertEquals(m.toString(), result.getModelAndView().getModel().get("user").toString());
}
}

调用Controller方法测试

无法对拦截器和URL路径配置进行测试。测试方法类似于service层单元测试,可以对依赖的service层进行mock。可以参考spring service层单元测试一文

被测试代码示例

测试代码同调用请求路径测试方式部分一样

测试代码示例

import com.agoura.agoura.entity.Members;
import com.agoura.agoura.service.MembersService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
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.setup.MockMvcBuilders; import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when; @RunWith(SpringJUnit4ClassRunner.class) //调用Spring单元测试类
@WebAppConfiguration //调用Java Web组件,如自动注入ServletContext Bean等
@ContextConfiguration(locations = {"classpath*:spring-*.xml"}) //加载Spring配置文件
public class MembersControllerTest {
@Mock
private MembersService service; @InjectMocks
private MembersController controller; //需要测试的Controller
private MockHttpServletRequest request; private MockMvc mockMvc; //SpringMVC提供的Controller测试类 @Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
request = new MockHttpServletRequest();
} @Test
public void testGetUser() throws Exception {
request.addParameter("userId", "100100"); // request.addParameter("id", "101010"); //如果需要从request取数据,可以在request中添加parameter Members m = new Members(3, "wangwu", 1, 5, "12131232342");
when(service.getMemberById(Mockito.anyInt())).thenReturn(m); String response = new String();
String result = controller.getUser(request, response, "3");
assertEquals(m.toString(), result);
}
}

Spring Controller单元测试的更多相关文章

  1. Spring MVC Controller 单元测试

    简介 Controller层的单元测试可以使得应用的可靠性得到提升,虽然这使得开发的时间有所增加,有得必失,这里我认为得到的比失去的多很多. Sping MVC3.2版本之后的单元测试方法有所变化,随 ...

  2. Spring Boot单元测试(Mock)

    Spring Boot单元测试(Mock) Java个人学习心得 2017-08-12 16:07 Mock 单元测试的重要性就不多说了,我这边的工程一般都是Spring Boot+Mybatis(详 ...

  3. Spring MVC学习总结(1)——Spring MVC单元测试

    关于spring MVC单元测试常规的方法则是启动WEB服务器,测试出错 ,停掉WEB 改代码,重启WEB,测试,大量的时间都浪费在WEB服务器的启动上,下面介绍个实用的方法,spring MVC单元 ...

  4. Spring MVC -- 单元测试和集成测试

    测试在软件开发中的重要性不言而喻.测试的主要目的是尽早发现错误,最好是在代码开发的同时.逻辑上认为,错误发现的越早,修复的成本越低.如果在编程中发现错误,可以立即更改代码:如果软件发布后,客户发现错误 ...

  5. Spring Boot 单元测试示例

    Spring 框架提供了一个专门的测试模块(spring-test),用于应用程序的单元测试. 在 Spring Boot 中,你可以通过spring-boot-starter-test启动器快速开启 ...

  6. Spring之单元测试

    引言 是否在程序运行时使用单元测试是衡量一个程序员素质的一个重要指标.使用单元测试既可以让我检查程序逻辑的正确性还可以让我们减少程序测试的BUG,便于调试可以提高我们写程序的效率.以前我们做单元测试的 ...

  7. jQuery 传递对象参数到Spring Controller

    当jQuery 发送ajax请求需要传递多个参数时,如果参数过多,Controller接收参数时就需要定义多个参数,这样接口方法会比较长,也不方便.Spring可以传递对象参数,将你需要的所有查询条件 ...

  8. postman传递对象到spring controller的方式

    1.spring Controller @RestController @RequestMapping(value = "/basic/task") public class Ta ...

  9. spring controller 获取context

    想要获取context需要先熟悉spring是怎么在web容器中启动的,spring启动过程其实就是其IOC容器的启动过程,对于web程序,IOC容器启动过程即是建立上下文的过程 spring启动过程 ...

随机推荐

  1. 跨web浏览器的IC卡读卡器解决方案

    BS结构的程序,如果要与IC卡读卡器通信本身就是件不容易解决的事情.微软的activex ocx技术将这种应用限制在IE浏览器上了,不兼容其它的浏览器.而Chrome使用插件也不兼容IE和其他的浏览器 ...

  2. 使用点击二分图计算query-document的相关性

    之前的博客中已经介绍了Ranking Relevance的一些基本情况(Click Behavior,和Text Match):http://www.cnblogs.com/bentuwuying/p ...

  3. SQL Server 中截取字符串常用的函数

    SQL Server 中截取字符串常用的函数: 1.LEFT ( character_expression , integer_expression ) 函数说明:LEFT ( '源字符串' , '要 ...

  4. 生产环境-jvm内存溢出-jprofile问题排查

    首先线上开启了dump的参数 dump的内容有2G,先进行压缩打包,传输至本地(scp) tar -czvf dump.tar java_pid4824.hprof  使用Jprofile打开dump ...

  5. 使用Asp.Net MVC开发兼职文章系统

    我已经开发好了,你拿去用就是了. 以下是README的内容,包含功能要求和开发过程的一些思考: 一.功能 1.学生兼职人员文章(任务.自由编写),审核(通过,退回修改,无效),并按每15天结算一次费用 ...

  6. DirectFB 之 实例图像不断右移

    /********************************************** * Author: younger.liucn@gmail.com * File name: imgro ...

  7. EasyUI开发的驾校管理系统

    开源SmartLife驾校管理系统,地址:https://github.com/SmartOfLife/DriveMgr 1.界面布局是用的ymnets大神的界面,具体参考:http://www.cn ...

  8. springmvc 导出excel

    1.pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www ...

  9. Python简要学习笔记

    1.搭建学习环境 推荐ActivePython,虽然此乃为商业产品,却是一个有自由软件版权保证的完善的Python开发环境,关键是文档以及相关模块的预设都非常齐备. ActivePython下载地址: ...

  10. 将 Eclipse 的配色改为黑底白字

    1.先到 eclipsecolorthemes下载一个主题. 2.Eclipse File-->Import 3.Import视窗内选择 General-->Preferences 4.选 ...