Spring-MockMvc

来源:互联网 发布:赵泓霖的网络课100节 编辑:程序博客网 时间:2024/06/15 15:06
1.写一个父类package 你的包;import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;import java.nio.charset.Charset;import org.junit.Before;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.http.MediaType;import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;import org.springframework.test.context.junit4.SpringRunner;import org.springframework.test.web.servlet.MockMvc;import org.springframework.web.context.WebApplicationContext;@RunWith(SpringRunner.class)@SpringBootTestpublic class SpringTestCase extends AbstractJUnit4SpringContextTests{    public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));    @Autowired    protected WebApplicationContext wac;    protected MockMvc mockMvc;    @Before    public void setup() throws Exception {        this.mockMvc = webAppContextSetup(this.wac).build();    }}2.测试类继承上边的类,下面是一个测试登录的集成测试,模拟发送HTTP post请求package 包名;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;import org.junit.Assert;import org.junit.Test;import org.springframework.http.MediaType;import org.springframework.test.web.servlet.MvcResult;import com.alibaba.fastjson.JSONObject;public class LoginTest2 extends SpringTestCase{    @Test    public void test() throws Exception {        JSONObject param = new JSONObject();        param.put("mobile", "16156536563");        param.put("password", "mima");        String actual = param.toJSONString();        System.out.println("============param===>" + actual);        MvcResult mvcResult = this.mockMvc                .perform(                        post("/login")                           .characterEncoding("UTF-8")                             .contentType(MediaType.APPLICATION_JSON)                           .content(actual)                                .header("deviceId", "bb")                        )                        .andDo(print()).andReturn();        int status = mvcResult.getResponse().getStatus();        Assert.assertEquals(200, status);          String result = mvcResult.getResponse().getContentAsString();          JSONObject jsonObject = JSONObject.parseObject(result);          Assert.assertEquals(true, jsonObject.containsKey("result"));        Assert.assertEquals(true, jsonObject.containsKey("resultCode"));        Assert.assertEquals(true, jsonObject.containsKey("resultMessage"));        Assert.assertEquals(true, jsonObject.containsKey("data"));    }}
阅读全文
0 0
原创粉丝点击