使用Mock 对spring mvc 的controller层进行单元测试

总体目标:达到自动化测试接口的目的

项目组成:spring mvc + hibernate + mysql

如何使用mock进行接口的单元测试?

实现思路:将mysql替换成h2数据库,之前hibernate 的datesource配置的是mysql,现在配置成h2,这样测试的数据库是干净的,因为在内存中。每次进行junit mock测试之前清空一下内存中的数据库即可

实现代码:

package cn.edu.hebtu.www.onemeet.client.controller;

import cn.edu.hebtu.www.onemeet.client.model.Company;
import cn.edu.hebtu.www.onemeet.client.model.Department;
import cn.edu.hebtu.www.onemeet.client.model.Me;
import cn.edu.hebtu.www.onemeet.common.model.Reply;
import cn.edu.hebtu.www.onemeet.common.web.filter.EncodeFilter;
import cn.edu.hebtu.www.onemeet.utils.TestUtils;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate4.support.OpenSessionInViewFilter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.jdbc.JdbcTestUtils;
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.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

import javax.sql.DataSource;
import java.util.List;

/**
 * mock测试,使用mock测试来保证接口的正确性
 * Created by chenzhibing on 15-10-30.
 */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(value = "src/main/webapp")
@ContextConfiguration(locations = {"classpath:spring.xml", "classpath:spring-hibernate-h2.xml"})
public class MockTest {
    private static Logger logger = Logger.getLogger(MockTest.class);
    @Autowired
    private WebApplicationContext wac;
    private MockMvc mockMvc;
    private JdbcTemplate template;
    @Autowired
    private EncodeFilter encodeFilter;
    @Autowired
    private OpenSessionInViewFilter openSessionInViewFilter;

@Autowired
    public void setDataSource(DataSource dataSource) {
        template = new JdbcTemplate(dataSource);
    }

@Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(this.encodeFilter, this.openSessionInViewFilter).build();
    }

@Before
    public void cleanData() {
        String script = "classpath:H2_Init.sql";
        Resource resource = wac.getResource(script);
        JdbcTestUtils.executeSqlScript(template, resource, true);
    }

@Test
    public void hello() throws Exception {
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/user/hello"))
                .andDo(print())
                .andReturn();
        String response = result.getResponse().getContentAsString();
        Reply reply = TestUtils.getStringReply(response);
        assertEquals(reply.getCode(), 1);
    }

@Test
    public void getCompanylist() throws Exception {
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/user/get_companylist"))
                .andDo(print())
                .andReturn();
        String response = result.getResponse().getContentAsString();
        Reply<List<Company>> reply = TestUtils.getCompanyListReply(response);
        assertEquals(reply.getCode(), 1);
        assertEquals(reply.getMsg().size(), 3);
        // assertEquals(reply.getMsg().get(0).getDepartList().size(), 4);
    }
  }

}

时间: 2024-08-24 19:35:13

使用Mock 对spring mvc 的controller层进行单元测试的相关文章

Spring MVC Test -Controller

http://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-mvc-controllers-configuration/ Writing unit tests for Spring MVC controllers has traditionally been both simple and problematic. Although it is pretty simple to write

Spring MVC 从 Controller向页面传值的方式

Spring MVC 从 Controller向页面传值的方式 在实际开发中,Controller取得数据(可以在Controller中处理,当然也可以来源于业务逻辑层),传给页面,常用的方式有:   1.利用ModelAndView页面传值 后台程序如下: @RequestMapping(value="/reciveData",method=RequestMethod.GET) public ModelAndView StartPage() { ModelMap map=new Mo

Spring MVC的Controller统一异常处理:HandlerExceptionResolver

出现异常并不可怕,可怕的是出现了异常,你却不知道,也没有进行异常处理. Spring MVC的Controller出现异常的默认处理是响应一个500状态码,再把错误信息显示在页面上,如果用户看到这样的页面,一定会觉得你这个网站太LOW了. 要解决Controller的异常问题,当然也不能在每个处理请求的方法中加上异常处理,那样太繁琐.Spring MVC提供了一个HandlerExceptionResolver接口,可用于统一异常处理. HandlerExceptionResolver接口 pu

Spring mvc框架 controller间跳转 ,重定向 ,传参

 一.需求背景 1. 需求:spring MVC框架controller间跳转,需重定向.有几种情况:不带参数跳转,带参数拼接url形式跳转,带参数不拼接参数跳转,页面也能显示. @RequestMapping(value = "/activityType", method = RequestMethod.GET) public String activityType(HttpServletRequest request, ModelMap model,RedirectAttribut

ZK Spring 整合View/Controller层属性注入

问题场景 ZK实例化的View/Controller不同于Spring MVC实例化的Controller,不受Spring管理,无法进行注入. 解决方案 方法一 在doAfterCompose方法中调用SpringUtil提供的获取bean的方法,给bean赋值,代码如下: userService = (UserService) SpringUtil.getBean("userService"); 方法二 在doAfterCompose方法中调用Spring的自动注入方法进行所有be

通过拦截器Interceptor实现Spring MVC中Controller接口访问信息的记录

java web工程项目使用了Spring+Spring MVC+Hibernate的结构,在Controller中的方法都是用于处理前端的访问信息,Controller通过调用Service进行业务处理后给前端返回ModelAndView对象或者只返回Json格式数据.如果能够获得Http请求在后端程序中处理的相关信息,对于开发和调试时十分方便的.工程中使用了Spring MVC的Interceptor对所有Http请求及其响应进行拦截,从而获取到本次访问接口信息以及程序处理时长等信息,特意在

spring mvc 注解@Controller @RequestMapping @Resource的详细例子

现在主流的Web MVC框架除了Struts这个主力 外,其次就是Spring MVC了,因此这也是作为一名程序员需要掌握的主流框架,框架选择多了,应对多变的需求和业务时,可实行的方案自然就多了.不过要想灵活运用Spring MVC来应对大多数的Web开发,就必须要掌握它的配置及原理. 一.Spring MVC环境搭建:(Spring 2.5.6 + Hibernate 3.2.0) 1. jar包引入 Spring 2.5.6:spring.jar.spring-webmvc.jar.comm

spring mvc 的Controller类是单例?

使用Spring MVC有一段时间了,之前一直使用Struts2,在struts2中action都是原型(prototype)的, 说是因为线程安全问题,对于Spring MVC中bean默认都是(singleton)单例的,那么用@Controller注解标签注入的Controller类是单例实现的? 测试结果发现spring3中的controller默认是单例的,若是某个controller中有一个私有的变量i,所有请求到同一个controller时,使用的i变量是共用的,即若是某个请求中修

SpringMVC Controller层的单元测试

Getting Ready 测试相关Maven dependency如下: <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.0.3.RELEASE</version> <scope>test</scope> </dependency> &