• 使用Mock 测试 controller层


    package action;

    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.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.ResultActions;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
    import org.springframework.test.web.servlet.setup.MockMvcBuilders;
    import org.springframework.web.context.WebApplicationContext;


    /**
    * Created by duanxinli on 2019/10/16.
    */
    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration()
    @ContextConfiguration({"classpath:application-context.xml","classpath:application-context-datasource.xml","classpath:springmvc-servlet.xml"})
    public class MVCTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;
    @Before
    public void init(){
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); //构造MockMvc
    }

    @Test
    public void getshortCutTest() throws Exception {
    ResultActions reaction=this.mockMvc.perform(MockMvcRequestBuilders.get("/shortcut/listAll")
    .accept(MediaType.APPLICATION_JSON));//返回值接收json
    reaction.andExpect(MockMvcResultMatchers.status().isOk());
    MvcResult mvcResult =reaction.andReturn();
    System.out.println(mvcResult.getResponse().getContentAsString());
    }

    @Test
    public void postshortCutTest() throws Exception {
    ResultActions reaction =this.mockMvc.perform(MockMvcRequestBuilders.post("/policy/info/save")
    .contentType(MediaType.APPLICATION_JSON)//请求体时json
    .header("Timestamp", "1496656373791")
    .header("AppId", "1003"));
    reaction.andExpect(MockMvcResultMatchers.status().isOk());
    MvcResult mvcResult =reaction.andReturn();
    System.out.println(mvcResult.getResponse().getContentAsString());
    }

    }
  • 相关阅读:
    写日志
    读写excel
    python安装模块
    数据库
    日志和关键字查找
    时间戳
    os 模块
    图-最小生成树算法之Kruskal及其Java实现
    图-图的表示、搜索算法及其Java实现
    前端实现list排序
  • 原文地址:https://www.cnblogs.com/duan2/p/11704310.html
Copyright © 2020-2023  润新知