首页 > 代码库 > Mock测试SpringMvc Controller 层的例子.

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 = http://www.mamicode.com/MAPPER.readValue(contentAsStrin, Map.class);"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;
    }

}

  

Mock测试SpringMvc Controller 层的例子.