Spring MVC Mock demo

package com.niwodai.mem.web.controller;

import com.alibaba.fastjson.JSON;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
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.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.util.HashMap;
import java.util.Map;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

/**
 * @Description:
 * @Author: zhaobo
 * @Date: 2017/10/17
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
@ActiveProfiles("dev")
public class MemGradeControllerTest {

    private Logger logger = LoggerFactory.getLogger(MemGradeControllerTest.class);

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void startUp(){
        mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void mock_memGrade_querySpecRights() throws Exception {
        String requestUrl = "/XXXXX";
        Map<String,String> queryParam = new HashMap<>();
        queryParam.put("name","TQ18");
        queryParam.put("offset","0");
        queryParam.put("limit","10");
        String jsonContent = JSON.toJSONString(queryParam);
        MvcResult result = mockMvc.perform(post(requestUrl)
                                            .content(jsonContent))
                                            .andReturn();
        MockHttpServletResponse response = result.getResponse();
        String resultContent = response.getContentAsString();
        logger.info("@@"+resultContent);
    }

}
原文地址:https://www.cnblogs.com/mengjianzhou/p/7738041.html