@SpringBootTest(classes = SpringBootGitApplication.class)
@RunWith(SpringRunner.class)
public class SpringBootMockMvc {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setup(){
// 测试代码执行前,需要执行的代码
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test // 上传文件测试
public void testFile() throws Exception {
String result = mockMvc.perform(MockMvcRequestBuilders.multipart("/test/file")
// MockMultipartFile类参数 1.属性名,2.文件的名字,3.内容类型,4.上传内容字节
.file(new MockMultipartFile("file",
"test.txt",
"multipart/form-data",
"hello upload".getBytes())))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
@Test // get请求测试
public void testGet() throws Exception {
String result = mockMvc.perform(MockMvcRequestBuilders.get("/"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
@Test // post请求测试
public void testPost() throws Exception {
Date date = new Date();
System.out.println(date.getTime());
String content = "{\"username\":\"li wen ya\",\"password\":null,\"birthday\":"+date.getTime()+"}";
String result = mockMvc.perform(MockMvcRequestBuilders.post("/user")
.contentType(MediaType.APPLICATION_JSON)
.content(content))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1))
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
}