由于项目中需要添加单元测试,所以查询之后发现Mockito非常适合现在的web项目。

首先需要添加pom依赖:

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
</dependency>

在ControllerTest类上需要添加如下配置:

//XML风格
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(value = "src/main/webapp")
@ContextHierarchy({
@ContextConfiguration(name = "parent", locations = "classpath:spring-config.xml"),
@ContextConfiguration(name = "child", locations = "classpath:spring-others.xml")
}) OR //注解风格
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(value = "src/main/webapp")
@ContextHierarchy({
@ContextConfiguration(name = "parent", classes = AppConfig.class),
@ContextConfiguration(name = "child", classes = MvcConfig.class)
})

MockMvc为spring测试下的一个非常好用的类,配合Mockito使用能达到非常好的效果,他们的初始化需要在setUp中进行,具体代码如下:

@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc; @Mock
private DemoService demoService; @Before
public void setUp() throws Exception {
// 构造appcontext
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
// 初始化Mock
MockitoAnnotations.initMocks(this);
}

这样mockMvc和Mockito的方法就可以在下面顺利使用了,例如:

@Test
public void testHelloWorld() throws Exception {
// 1. controller mvc test
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/demo/hello"))
    .andExpect(MockMvcResultMatchers.handler().handlerType(DemoController.class))
    .andExpect(MockMvcResultMatchers.handler().methodName("helloWorld"))
    .andExpect(MockMvcResultMatchers.view().name("demo/hello"))
    .andExpect(MockMvcResultMatchers.model().attributeExists("msg"))
    .andExpect(MockMvcResultMatchers.status().isOk())
    .andDo(MockMvcResultHandlers.print())
    .andReturn();
Assert.assertNotNull(result.getModelAndView().getModel().get("msg")); // 2. demo service stub test
String stub = "except result";
Mockito.when(demoService.demoShow()).thenReturn(stub);
Assert.assertEquals(stub, demoService.demoShow());
Mockito.verify(demoService).demoShow();
}

MockMvc可以对controller中的一次调用进行模拟,perform就是一次请求,MockMvcRequestBuilders进行url的请求,andExcept方法为对Controller类、调用方法、视图和model的预期设置,andDo进行这次请求的执行,最后andReturn返回。

Mockito通过方法when()、thenReturn()等方法可以对方法进行打桩,让后续方法按照自己的数据桩来返回,达到了隔离依赖的效果。

整体的测试代码如下:

import com.demo.service.DemoService;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
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.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; /**
* DemoControllerTest.
*/
//注解风格
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(value = "src/main/webapp")
@ContextHierarchy({
@ContextConfiguration(name = "parent", locations = "classpath:spring-config.xml")
})
public class DemoControllerTest { @Autowired
private WebApplicationContext wac;
private MockMvc mockMvc; @Mock
private DemoService demoService; @Before
public void setUp() throws Exception {
// 构造appcontext
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
// 初始化Mock
MockitoAnnotations.initMocks(this);
} @Test
public void testIndex() throws Exception {
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/demo/"))
.andExpect(MockMvcResultMatchers.handler().handlerType(DemoController.class))
.andExpect(MockMvcResultMatchers.handler().methodName("index"))
.andExpect(MockMvcResultMatchers.view().name("demo/index"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn(); Assert.assertNotNull(result.getModelAndView().getViewName());
} @Test
public void testHelloWorld() throws Exception {
// 1. controller mvc test
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/demo/hello"))
.andExpect(MockMvcResultMatchers.handler().handlerType(DemoController.class))
.andExpect(MockMvcResultMatchers.handler().methodName("helloWorld"))
.andExpect(MockMvcResultMatchers.view().name("demo/hello"))
.andExpect(MockMvcResultMatchers.model().attributeExists("msg"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
Assert.assertNotNull(result.getModelAndView().getModel().get("msg")); // 2. demo service stub test
String stub = "except result";
Mockito.when(demoService.demoShow()).thenReturn(stub);
Assert.assertEquals(stub, demoService.demoShow());
Mockito.verify(demoService).demoShow();
}
}

MockMvc和Mockito之酷炫使用的更多相关文章

  1. Android常用酷炫控件(开源项目)github地址汇总

    转载一个很牛逼的控件收集帖... 第一部分 个性化控件(View) 主要介绍那些不错个性化的 View,包括 ListView.ActionBar.Menu.ViewPager.Gallery.Gri ...

  2. 纯CSS3实现的一些酷炫效果

    之前在网上看到一些用纯CSS3实现的酷炫效果,以为实现起来比较困难,于是想看看具体是怎么实现的. 一.笑脸猫动画 实现效果如下: 这个实现起来确实比较麻烦,很多地方需要花时间,有耐心地调整. 1.先看 ...

  3. 三分钟学会用 js + css3 打造酷炫3D相册

    之前发过该文,后来不知怎么回事不见了,现在重新发一下. 中秋主题的3D旋转相册 如图,这是通过Javascript和css3来实现的.整个案例只有不到80行代码,我希望通过这个案例,让正处于迷茫期的j ...

  4. 【CSS进阶】试试酷炫的 3D 视角

    写这篇文章的缘由是因为看到了这个页面: 戳我看看(移动端页面,使用模拟器观看) 运用 CSS3 完成的 3D 视角,虽然有一些晕3D,但是使人置身于其中的交互体验感觉非常棒,运用在移动端制作一些 H5 ...

  5. HTML5 Canvas玩转酷炫大波浪进度图

    如上图所见,本文就是要实现上面那种效果. 由于最近AlloyTouch要写一个下拉刷新的酷炫loading效果.所以首选大波浪进度图. 首先要封装一下大波浪图片进度组件.基本的原理是利用Canvas绘 ...

  6. html5+Canvas实现酷炫的小游戏

    最近除了做业务,也在尝试学习h5和移动端,在这个过程中,学到了很多,利用h5和canvas做了一个爱心鱼的小游戏.点这里去玩一下 PS: 貌似有点闪屏,亲测多刷新两下就好了==.代码在本地跑都不会闪, ...

  7. 纯CSS3写的10个不同的酷炫图片遮罩层效果【转】

    这个是纯CSS3实现的的10个不同的酷炫图片遮罩层效果,可以欣赏一下 在线预览 下载地址 实例代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ...

  8. css3实现酷炫的3D盒子翻转效果

    简介 运用css3先在平面空间组成立方体盒子,再让整个盒子翻转起来,先来张效果图: 步骤 1.先用css将6张图片摆成下图的样子: 下面就是通过css3的3D变换将每个面进行翻转,使之成为一个立体的盒 ...

  9. [Asp.net 开发系列之SignalR篇]专题二:使用SignalR实现酷炫端对端聊天功能

    一.引言 在前一篇文章已经详细介绍了SignalR了,并且简单介绍它在Asp.net MVC 和WPF中的应用.在上篇博文介绍的都是群发消息的实现,然而,对于SignalR是为了实时聊天而生的,自然少 ...

随机推荐

  1. leetcode:两个数的和||

    两个数的和|| 给定一个排序数组,求出其中两个数的和等于指定target时,这两个数在原始数组中的下标,返回的下标从1开始 解题 原始数组已经是升序的,找出其中两个数的和等于target 定义两个指针 ...

  2. iOS开发网络篇--NSURLConnection

    S简介 NSURLConnection: 作用: 1.负责发送请求,建立客户端和服务器的连接发送数据给服务器 2.并收集来自服务器的响应数据 步骤: 1.创建一个NSURL对象,设置请求路径 2.传入 ...

  3. 47. Permutations II

    题目: Given a collection of numbers that might contain duplicates, return all possible unique permutat ...

  4. java--面向抽象编程

    所谓面向抽象编程是指当设计某种重要的类时,不让该类面向具体的类,而是面向抽象类,及所设计类中的重要数据是抽象类声明的对象,而不是具体类声明的对象.就是利用abstract来设计实现用户需求. 比如:我 ...

  5. CY7C68013A的一点总结

    一. 值得参考的资料:FX2 TechRefManual.USB应用开发宝典. LabVIEW-USB通信简单教程(用于参考生成labview驱动程序).USB设备请求和描述符整理(仅用于理解描述符的 ...

  6. Oracle SQL大全

    一. 基本操作表和数据 -- 建表 CREATE TABLE ab_student ( id number(4) ) create table ab_class( id number(4), name ...

  7. sh.exe": grunt: command not found

    今天在git命令行工具中使用 grunt的时候,总是提示我找不到grunt命令,如: sh.exe": grunt: command not found 但是我运行 npm install ...

  8. linux/unix网络编程之epoll

    转载自 Linux epoll模型 ,这篇文章讲的非常详细! 定义: epoll是Linux内核为处理大批句柄而作改进的poll,是Linux下多路复用IO接口select/poll的增强版本,它能显 ...

  9. 命名空间“System.Web”中不存在类型或命名空间名称“Script”(是缺少程序集引用吗?)

    网上有些资料说,在项目上鼠标右键,添加引用→.Net→System.Web.Entensions就可以了. 实际上很多时候在项目中的添加引用窗口上,根本找不到System.Web.Entensions ...

  10. Jqgrid入门-操作表格的数据(二)

    上一篇中,Jqgrid已经可以从服务端获得数据,并显示在Grid表格中了.下面说一下,如何操作表格及其数据.           jqGrid有很多方法函数,用来操作数据或者操作Grid表格本身.jq ...