美文网首页
MockMvc 模拟请求

MockMvc 模拟请求

作者: 61etj | 来源:发表于2018-12-18 23:24 被阅读0次

    MockMvc 的使用

    用来快速模拟请求

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class UserControllerTest {
    
        @Autowired
        private WebApplicationContext wac;
    
        private MockMvc mockMvc;
    
        @Before
        public void setup(){
            //1.初始化
            mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
        }
    
    
        @Test
        public void whenUploadSuccess() throws Exception {
            //2.使用
            String reuslt = mockMvc.perform(MockMvcRequestBuilders.fileUpload("/file")
                    .file(new MockMultipartFile("file","test.txt","multipart/form-data","hello word".getBytes())))
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    .andReturn().getResponse().getContentAsString();
    
            System.out.println(reuslt);
        }
    
        @Test
        public void whenQuerySuccess() throws Exception {
            String result = mockMvc.perform(MockMvcRequestBuilders.get("/user")
                    .param("username","jojo")
                    .param("age","18")
                    .param("ageTo","60")
                    .param("size","15")
                    .param("page","3")
                    .param("sort","age,desc")
                    //.content(content))  content为json字符串
                    .contentType(MediaType.APPLICATION_JSON_UTF8))
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3))
                    .andReturn().getResponse().getContentAsString();
            System.out.println(result);
        }
    
    }
    

    相关文章

      网友评论

          本文标题:MockMvc 模拟请求

          本文链接:https://www.haomeiwen.com/subject/rhorkqtx.html