zoukankan      html  css  js  c++  java
  • 使用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());
    }

    }
  • 相关阅读:
    StringBuilder方法的使用
    软件开发一般分为五个阶段
    HTML与XML的区别(转)
    经常调用的WebServce的方法有哪些?
    1-2+3-4+........+M方法一;方法二
    查找Dom树中所有<li>的元素,并改变其内容
    判断月份是否小于10的写法
    Repeater绑定页面的方法
    转换int类型TryParse的作用
    【转】【java源码分析】Map中的hash算法分析
  • 原文地址:https://www.cnblogs.com/duan2/p/11704310.html
Copyright © 2011-2022 走看看