package com.cjy.user;
import com.alibaba.fastjson.JSONObject;
import com.cjy.interceptor.Page;
import org.junit.Before;
import org.junit.Test;
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.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
/**
* @author Cheng JiYe
* @description:
* @date 2020/8/5 10:57
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
// 注入web环境的ApplicationContext容器
@Autowired
private WebApplicationContext context;
/**
* 模拟mvc测试对象
*/
private MockMvc mockMvc;
/**
* 所有测试方法执行之前执行该方法
*/
@Before // 这个注解的作用,在每个方法之前都会执行一遍
public void before() throws Exception {
//获取mockmvc对象实例
mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
@Test
public void getInfo() throws Exception {
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.get("/user/getInfo")
.param("username", "Jack")
.param("password", "Jack001"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print()).andReturn();
System.out.println("输出 " + mvcResult.getResponse().getContentAsString());
}
@Test
public void list2() throws Exception {
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.post("/user/list22")
.param("name", "张三"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print()).andReturn();
System.out.println("输出 " + mvcResult.getResponse().getContentAsString());
}
/**
* 传递单个参数
*
* @throws Exception
*/
@Test
public void list4() throws Exception {
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.post("/user/list4")
.param("name", "张三"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print()).andReturn();
System.out.println("输出 " + mvcResult.getResponse().getContentAsString());
}
/**
* 测试传递 @RequestBody ,传递对象
*
* @throws Exception
*/
@Test
public void list5() throws Exception {
Page page = new Page();
page.setName("张三");
String paraJson = JSONObject.toJSONString(page);
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/user/list4").contentType(MediaType.APPLICATION_JSON).content(paraJson))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print()).andReturn();
System.out.println("输出 " + mvcResult.getResponse().getContentAsString());
}
}