由于项目中需要添加单元测试,所以查询之后发现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. hdu1116

    http://acm.hdu.edu.cn/showproblem.php?pid=1116 #include<stdio.h> #include<math.h> #inclu ...

  2. python自定义函数在Python解释器中调用

    https://docs.python.org/2.7/tutorial/modules.html Modules If you quit from the Python interpreter an ...

  3. P1023 奶牛的锻炼

    P1023 奶牛的锻炼 时间: 1000ms / 空间: 131072KiB / Java类名: Main 背景 USACO 描述 奶牛Bessie有N分钟时间跑步,每分钟她可以跑步或者休息.若她在第 ...

  4. 李洪强iOS开发之keychain的使用

    通常情况下,我们用NSUserDefaults存储数据信息,但是对于一些私密信息,比如密码.证书等等,就需要使用更为安全的keychain了.keychain里保存的信息不会因App被删除而丢失,在用 ...

  5. LeeCode 1-Two Sum

    Two Sum Total Accepted: 125096 Total Submissions: 705262 Question Solution Given an array of integer ...

  6. lintcode:合并排序数组

    题目: 合并排序数组 合并两个排序的整数数组A和B变成一个新的数组. 样例 给出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6] 挑战 你能否优化你的算法,如果 ...

  7. OPenGL中三维图形的矩阵变换

    对于二维的图形开发,拿简单的图片显示来说,我们主要的目的:就是在一块显示buffer中,不停的把每个像素进行着色,然后就可以绘制出来了.为了速度,很多其他的加速方法,但原理基本上就是这样了. 很直观, ...

  8. 爬虫Larbin解析(一)——Larbin配置与使用

    介绍 功能:网络爬虫 开发语言:c++ 开发者:Sébastien Ailleret(法国) 特点:只抓取网页,高效(一个简单的larbin的爬虫可以每天获取500万的网页) 安装 安装平台:Ubun ...

  9. Zookeeper集群和HBase集群

    1.部署Zookeeper集群(hadoop0\hadoop1\hadoop2) 1.1.在hadoop0上解压缩Zookeeper-3.4.5.tar.gz 1.2.执行命令 cp conf/zoo ...

  10. C# Index 定义索---引具体使用2

    窗体代码 using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;usi ...