Mock测试SpringMvc Controller 层的例子.

spring version : 4.1.6.RELEASE

Junit version : 2.4.5

package com.shiji.soc.es.controller;

import static org.junit.Assert.*;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shiji.soc.es.dao.SocDao;
import com.shiji.soc.es.dto.SocField;
import com.shiji.soc.es.dto.SocRequest;
import com.shiji.soc.es.enums.FieldType;
import com.shiji.soc.es.service.SocService;

@SuppressWarnings("rawtypes")
@ContextConfiguration({ "classpath:spring/soc-applicationContext.xml", "classpath:spring/soc-springmvc.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class SocControllerTest {
    private static ObjectMapper MAPPER = new ObjectMapper();
    @Autowired
    SocDao socDao;
    @Autowired
    SocService socService;

    @Autowired
    SocController socController;
    protected MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(socController).build();
    }

    @Test
    public void testPostMethod() throws Exception {
        String queryJson = this.getQueryJson();
        MvcResult andReturn = mockMvc
                .perform(//
                        MockMvcRequestBuilders//
                                .post("/query")//
                                .contentType(MediaType.APPLICATION_JSON)//
                                .content(queryJson)//
                                .accept(MediaType.APPLICATION_JSON)) // 执行请求
                .andReturn();
        MockHttpServletResponse response = andReturn.getResponse();
        // response.getContentAsString(); 就是服务器controller 返回的json 字符串.
        // response.getStatus(); http响应码 200之类.
        // response.getCookies();  服务器返回的Cookie[]
        this.piringAndAssert(response);
    }

    @Test
    public void testGetMethod() throws Exception {
        System.out.println("socDao is null ? " + (socDao == null));
        System.out.println("socService is null ? " + (socService == null));
        System.out.println("socController is null ? " + (socController == null));
        System.out.println("mockMvc is null ? " + (mockMvc == null));

        MvcResult mvcResult = this.mockMvc.perform(//
                MockMvcRequestBuilders.get("/query")//
        ).andReturn();

        MockHttpServletResponse response = mvcResult.getResponse();
        String result = response.getContentAsString();
        System.out.println("=====resp :\n" + result);
        // System.out.println(mvcResult.getResponse().getStatus());
        System.out.println("status : " + response.getStatus());
        System.out.println("cookies  : " + Arrays.asList(response.getCookies()));

        System.out.println(response);
    }

    private void piringAndAssert(MockHttpServletResponse response) {

        try {
            System.out.println("###status : " + response.getStatus());
            String contentAsStrin = null;
            contentAsStrin = response.getContentAsString();

            System.out.println(contentAsStrin);

            Map readValue = MAPPER.readValue(contentAsStrin, Map.class);

            List list = (List) readValue.get("results");
            if (list == null) {
                System.out.println("###result is null !! ");
            } else {
                for (Object object : list) {
                    System.out.println(object);
                }
            }

            System.out.println("###page =" + readValue.get("page"));
            System.out.println("###size =" + readValue.get("size"));
            System.out.println("###count =" + readValue.get("count"));
            System.out.println("###respCode =" + readValue.get("respCode"));
            System.out.println("###respText =" + readValue.get("respText"));
            System.out.println("###errorCode =" + readValue.get("errorCode"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getQueryJson() {
        HashSet<String> set = new HashSet<String>();
        set.add("apiPassword10030");
        set.add("apiPassword10064");
        set.add("apiPassword10142");
        set.add("apiPassword10129");

        SocRequest bean = new SocRequest();

        List<SocField> query = Arrays.asList(//
                new SocField("groupId", FieldType.MATCH.getType(), 0), //
                new SocField("apiPassword", FieldType.SET.getType(), set), //
                new SocField("txnDateTime", FieldType.RANGE.getType(), 1496817450449L, 1496817455610L)//
        );

        bean.setQuery(query);
        List<String> column = Arrays.asList("txnNo", "txnDateTime", "terId", "apiUser");

        bean.setColumns(column);

        bean.setPage(1);
        bean.setSize(20);
        String writeValueAsString = null;
        try {
            writeValueAsString = MAPPER.writeValueAsString(bean);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return writeValueAsString;
    }

}

  

时间: 2024-11-10 01:26:44

Mock测试SpringMvc Controller 层的例子.的相关文章

使用MockMvc测试SpringMVC Controller

MockMvc 是springTest提供的对SpringMvc提供的测试工具.这样可以让单元测试不仅仅局限于对Dao和Service 层的测试.同时,也可以测试Controller层.丰富的单元测试的功能.测试时不用频繁重启servlet容器,简化了测试操作. MockMvc需要ServletContext来模拟用户的请求和相应. 首选,需要在测试类头部添加一下Annotation @WebAppConfiguration @RunWith(SpringJUnit4ClassRunner.cl

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> &

springmvc,controller层在接收浏览器url传来的参数带中文乱码问题。

请求地址:http://localhost:8080/saveFlashSale?fsRemark=哈哈哈哈哈 接收方法:@RequestMapping("/saveFlashSale") public Msg saveFlashSale(FlashSale sale) 实体FlashSale接收到的fsRemark是乱码. 分析:在接收了的时候就是乱码了,那就用排除法. eclipse:widow->Perference->General->Workspace:是u

Spring MVC如何测试Controller(使用springmvc mock测试)

在springmvc中一般的测试用例都是测试service层,今天我来演示下如何使用springmvc mock直接测试controller层代码. 1.什么是mock测试? mock测试就是在测试过程中,对于某些不容易构造或者不容易获取的对象,用一个虚拟的对象来创建以便测试的测试方法. 2.为什么要使用mock测试? 使用Mock Object进行测试,主要是用来模拟那些在应用中不容易构造(如HttpServletRequest必须在Servlet容器中才能构造出来)或者比较复杂的对象(如JD

Spring自带mock测试Controller

转自:http://blog.csdn.net/yin_jw/article/details/24726941 分类: Spring开源框架2014-04-29 17:01 1786人阅读 评论(2) 收藏 举报 Spring自带mock测试Contro 准备SpringMVC环境 注意:使用mock测试需要引入spring-test包 Base类:加载配置文件 [java] view plaincopy package com.wyy.snail.user.controller; import

Junit mockito 测试Controller层方法有Pageable异常

1.问题 在使用MockMVC+Mockito模拟Service层返回的时候,当我们在Controller层中参数方法调用有Pageable对象的时候,我们会发现,我们没办法生成一个Pageable的对象,会报一个Pageable是一个接口的错误.当我们把所有的参数从Pageable接口变成Pageable的实现类PageRequest的时候,所有的方法参数都换成PageRequest,又会出现一个新的错误,且不说PageRequest不能作为参数用于hibernate的分页查询,另一方面,它没

使用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

SpringBoot测试Controller层

一.准备工作 1.导入测试依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> 2.Controller层: @RestController("/") public class UserController { @Autow

spring-mvc 非 controller 层获取HttpServletRequest

在项目中记录操作日志,是一种很常见的需求. 有时我们在service或者dao层记录日志,需要同时保存访问ip.登录用户名等.如果从controller层把HttpServletRequest 对象传过去会显得很麻烦.HttpSession可以通过HttpServletRequest 间接获取. 在web.xml配置 <listener>   <listener-class>org.springframework.web.context.request.RequestContext