mock数据测试,模拟http请求

第一步:导入支持包


<dependency>
  <groupId>org.mockitogroupId>
  <artifactId>mockito-allartifactId>
  <version>1.9.5version>
  <scope>testscope>
dependency>

第二步 编写代码

package im.qingtui.operation.omp;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

/**
 * 用mock数据测试的方法进行请求测试
 *
 * @author jiajia
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
    "/spring/dispatcherServlet.xml",
    "/spring/applicationContext.xml"})
public class RequestTest {
    private MockMvc mockMvc;

    @Autowired
    StatisticController statisticController;

    @Before
    public void setup() {
// initialize mock object
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(statisticController).build();
    }


    /**
     * 测试分区统计查询
     * @throws Exception
     */
    @Test
    public void testPartitionStatistic() throws Exception {
        this.mockMvc
            .perform(MockMvcRequestBuilders.get("/test/test")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .param("str1", "36271b94630f45a589a4791dde9fe4a7")
                .param("str2", "1517414399999")
                .param("start", "1514736000000")
                .param("selfAccountId", "ee3b9ffbb3e946899929882b4711b57d"))
            .andDo(print()).andExpect(status().isOk())
            .andExpect(content().contentType("application/json;charset=UTF-8")).andReturn().getResponse()
            .getContentAsString();
    }
}
结果 : 可以从控制台看到请求参数和对应的返回参数

你可能感兴趣的:(笔记)