• 使用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());
    }

    }
  • 相关阅读:
    Java:day4
    Java:day3
    Java:day2
    Java学习的第一天
    void指针
    const* 和 *const
    指针数组和数组指针
    c++的const
    C语言基础总结
    C、C++、java中的static区别
  • 原文地址:https://www.cnblogs.com/duan2/p/11704310.html
Copyright © 2020-2023  润新知